-3

For example, I have some Student:

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

So expected output should be like this:

finalList = [Student{name='Tom', age=32}, Student{name='Jack', age=19}]

============Worked solution=============

List<Student> result = rawListStudents.stream()
    .collect(Collectors.toMap(Student::getName, Function.identity(), (v1, v2) -> new Student(v2.getName(), v1.getAge() + v2.getAge())))
    .values()
    .stream()
    .toList();

Anyway, it seems there is no opportunity to merge list without additional steps with temporary map.

Tom
  • 73
  • 1
  • 8

1 Answers1

2

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());
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
AddeusExMachina
  • 592
  • 1
  • 11
  • 22