Java 8 EnumMap List with Amounts

I have the following classes:

public class Mark {

    private Long id;

    private Student student;

    private Integer value = 0;

    private Subject subject;

}

public enum Subject {

    MATH,
    CHEMISTRY

}

I need to get EnumMap<Subject, Integer>where the value is the sum of all the values ​​from Mark.
An example List<Mark>:

Mark (..., value = 1, subject = MATH)
Mark (..., value = 2, subject = MATH)
Mark (..., value = 5, subject = CHEMISTRY)

with this value, I should get the following EnumMap:

MATHEMATICS → 3
CHEMISTRY → 5

I think this should be done with help Collectors::groupingBy, but I can’t figure out how to get EnumMapits meaning.

+4
source share
1 answer
 markList.stream().collect(
     groupingBy(
         Mark::getSubject,
         () -> new EnumMap<Subject, Integer>(Subject.class),
         summingInt(Mark::getValue)));
+7
source

Source: https://habr.com/ru/post/1667207/


All Articles