Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to edit list with streams without making new map?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading