一层分组
List<MoocSchoolRecord> coursePeriod = new ArrayList<>();
coursePeriod.add(new MoocSchoolRecord().setCreditHour(10d).setUserId(1L));
coursePeriod.add(new MoocSchoolRecord().setCreditHour(20d).setUserId(1L));
coursePeriod.add(new MoocSchoolRecord().setCreditHour(30d).setUserId(2L));
Map<Long,List<MoocSchoolRecord>> map = coursePeriod.stream().collect(Collectors.groupingBy(MoocSchoolRecord::getUserId));
for (Map.Entry<Long, List<MoocSchoolRecord>> longListEntry : map.entrySet()) {
System.out.println(longListEntry.getKey()+"--"+longListEntry.getValue().size());
}
输出
1--2
2--1
二层分组
下面先根据 userId进行分组 再根据 CreditHour 分组 (代码描述和实际代码运行逻辑无关)
List<MoocSchoolRecord> coursePeriod = new ArrayList<>();
coursePeriod.add(new MoocSchoolRecord().setCreditHour(10d).setUserId(1L));
coursePeriod.add(new MoocSchoolRecord().setCreditHour(20d).setUserId(1L));
coursePeriod.add(new MoocSchoolRecord().setCreditHour(20d).setUserId(1L));
coursePeriod.add(new MoocSchoolRecord().setCreditHour(20d).setUserId(1L));
coursePeriod.add(new MoocSchoolRecord().setCreditHour(30d).setUserId(2L));
coursePeriod.add(new MoocSchoolRecord().setCreditHour(30d).setUserId(2L));
coursePeriod.add(new MoocSchoolRecord().setCreditHour(30d).setUserId(2L));
Map<Long, Map<Double, List<MoocSchoolRecord>>> map = coursePeriod.stream().collect(Collectors.groupingBy(MoocSchoolRecord::getUserId,Collectors.groupingBy(MoocSchoolRecord::getCreditHour)));
for (Map.Entry<Long, Map<Double, List<MoocSchoolRecord>>> longMapEntry : map.entrySet()) {
System.out.println("#"+longMapEntry.getKey());
for (Map.Entry<Double, List<MoocSchoolRecord>> school : longMapEntry.getValue().entrySet()) {
System.out.println("##"+school.getKey()+"-"+school.getValue().size());
}
}
输出
#1
##20.0-3
##10.0-1
#2
##30.0-3