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 have to receive EnumMap, where the value is the sum of all values from the Mark.
Example of List:
Mark(..., value = 1, subject = MATH)
Mark(..., value = 2, subject = MATH)
Mark(..., value = 5, subject = CHEMISTRY)
with that value I have to receive the following EnumMap:
MATH -> 3
CHEMISTRY -> 5
I think it should be done with Collectors::groupingBy, but I can't understand how to get EnumMap and his value.
解决方案
markList.stream().collect(
groupingBy(
Mark::getSubject,
() -> new EnumMap(Subject.class),
summingInt(Mark::getValue)));