Home > front end >  How to edit list with streams without making new map?
How to edit list with streams without making new map?

Time:07-22

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}]

I have worked solution with cycles but it's too long...

    final Map<String, List<Student>> groupedStudents = students.stream()
        .collect(Collectors.groupingBy(Student::getName));

    List<Student> resultList = new ArrayList();

    for (List<Student> st : groupedStudents.values()) {
        if (st.size() == 1) {
            resultList.add(st.get(0));
        } else {
            int finalAge = 0;
            for (int i = 0; i < st.size(); i  ) {
                finalAge  = st.get(i).getAge();
            }
            Student temp = new Student(st.get(0).getName(), finalAge);
            resultList.add(temp);
        }
    }

CodePudding user response:

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());
  • Related