我有一个类似于List的Student类的对象列表。学生班级上有日期和另一个班级对象的排序图见下文:
class Student{
String name;
SortedMap<LocalDate, Score> semScore = new TreeMap()<>;
}
class Score{
int score;
String grade;
}
我如何汇总学生列表,以按学生姓名将所有排序的地图合并到单个地图组中。对于例如
Score score = new Score(90, "A");
SortedMap<LocalDate, Score> sMap = new TreeMap<>();
sMap.put(LocalDate.now(), score);
Student s = new Student("Bob", sMap);
So multiple records are in the list for a Student with a given name with one map of score.
I need to aggregate all the scores into the same student object like group by name.
How can we do it using java streams?
Thanks
由于必须合并它们,所以Collectors#toMap
包含合并功能:
Map<String, Student> mergedStudents = list.stream().collect(Collectors.toMap(Student::getName, Function.identity(), (s1, s2) -> {
SortedMap<LocalDate, Score> semScore = new TreeMap<>(s1.getSemScore());
semScore.putAll(s2.getSemScore());
return new Student(s1.getName(), semScore);
}));