【问题标题】:Group list of objects with the same id/name using java stream使用 java 流对具有相同 ID/名称的对象进行分组
【发布时间】:2020-09-06 16:38:29
【问题描述】:

我有一个学生类的对象列表,例如列表。学生班级有另一个班级分数的日期和对象的排序图 见下文:

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

【问题讨论】:

    标签: lambda java-8 java-stream collectors


    【解决方案1】:

    因为您必须将它们合并,所以 Collectors#toMapcomprises 的合并函数:

    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);
    }));
    

    【讨论】:

    • 可以修改现有的并在merge函数中返回吗?
    • 是的。只需将 s2.semScore 添加到 s1 并返回 s1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2020-02-22
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    相关资源
    最近更新 更多