For example, I have some Student:
@Data
@ToString
class Student{
private String name;
private int age;
}
And I have a list of Students:
Student st1 = new Student("Tom", 14);
Student st2 = new Student("Tom", 18);
Student st3 = new Student("Jack", 19);
I know how I can group them by name using GroupingBy function, but how can I modify list just summing the total age of students with same names?
So expected output should be like this:
finalList = [Student{name='Tom', age=32}, Student{name='Jack', age=19}]
>Solution :
The link suggested by @Federico klez Culloca may be useful, I suggest you looking at this section https://www.baeldung.com/java-groupingby-collector#7-getting-the-sum-from-grouped-results
List<Student> result = students.stream()
.collect(groupingBy(Student::getName, summingInt(Student::getAge)))
.entrySet()
.stream()
.map(x -> new Student(x.getKey(), x.getValue()))
.collect(Collectors.toList());