@Test public void testGroup2() { //1.分組計數 更具classId分組,計算個數 List<Student> list1 = Arrays.asList( new Student(1L, "one", "oneS1"), new Student(2L, "one", "oneS2"), new Student(3L, "one", "oneS3"), new Student(4L, "tow", "towS1"), new Student(5L, "tow", "towS2"), new Student(6L, "three", "sun")); //[1, 2, 3, 4, 5, 6] List<Long> sId = list1.stream().map(item -> item.getId()).collect(Collectors.toList()); System.out.println(sId); //{ // one=[Student(id=1, classId=one, name=oneS1), Student(id=2, classId=one, name=oneS2), Student(id=3, classId=one, name=oneS3)], // three=[Student(id=6, classId=three, name=sun)], // tow=[Student(id=4, classId=tow, name=towS1), Student(id=5, classId=tow, name=towS2)] //} Map<String, List<Student>> collect = list1.stream().collect(Collectors.groupingBy(Student::getClassId)); System.out.println(collect); //1.1根據某個屬性分組計數 //{one=3, three=1, tow=2} Map<String, Long> result1 = list1.stream().collect(Collectors.groupingBy(Student::getClassId, Collectors.counting())); System.out.println(result1); //1.3根據分組的key值對結果進行排序、放進另外一個map中並輸出 //comparingByKey //{one=3, tow=2, three=1} Map<String,Long> xMap=new HashMap<>(); result1.entrySet().stream().sorted(Map.Entry.<String,Long>comparingByValue().reversed()).forEachOrdered(x->xMap.put(x.getKey(),x.getValue())); System.out.println(xMap); //2.分組,並統計其中一個屬性值得sum或者avg:id總和 /** {one=LongSummaryStatistics{count=3, sum=6, min=1, average=2.000000, max=3}, three=LongSummaryStatistics{count=1, sum=6, min=6, average=6.000000, max=6}, tow=LongSummaryStatistics{count=2, sum=9, min=4, average=4.500000, max=5}} */ Map<String, LongSummaryStatistics> summaryStatisticsMap = list1.stream().collect(Collectors.groupingBy(Student::getClassId, Collectors.summarizingLong(Student::getId))); System.out.println(summaryStatisticsMap); }