Listコレクション内の複数のデータは、オブジェクトのあるフィールドに基づいてマージされる
13970 ワード
Studioクラスの作成
方法1:
Javaのmapで実現
方法2:
Java 8で実現
@Data
@AllArgsConstructor
private static class Student {
private Integer id;
private String name;
private Integer age;
}
方法1:
Javaのmapで実現
List<Student> list = new ArrayList<>();
list.add(new Student(1, " ", 10));
list.add(new Student(2, " ", 20));
list.add(new Student(1, " ", 30));
Map<Integer, Student> map = new HashMap<>();
for (Student student : list) {
Integer id = student.getId();
if (map.containsKey(id)) {
Student s = map.get(id);
s.setAge(s.getAge() + student.getAge());
map.put(id, s);
} else {
map.put(id, student);
}
}
List<Student> studentList = new ArrayList<>();
for(Integer temp:map.keySet()){
studentList.add(map.get(temp));
}
System.out.println(studentList);
//[StreamTest.Student(id=1, name= , age=40), StreamTest.Student(id=2, name= , age=20)]
方法2:
Java 8で実現
List<Student> list = new ArrayList<>();
list.add(new Student(1, " ", 10));
list.add(new Student(2, " ", 20));
list.add(new Student(1, " ", 30));
List<Student> studentList = new ArrayList<>();
list.parallelStream().collect(Collectors.groupingBy(Student::getId, Collectors.toList()))
.forEach((id, transfer) -> {
transfer.stream().reduce((a, b) -> new Student(a.getId(), a.getName(), a.getAge() + b.getAge())).ifPresent(studentList::add);
});
System.out.println(studentList);
//[StreamTest.Student(id=1, name= , age=40), StreamTest.Student(id=2, name= , age=20)]