Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 List to EnumMap with sums

Tags:

java

java-8

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<Subject, Integer>, where the value is the sum of all values from the Mark.
Example of List<Mark>:

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.

like image 890
Feeco Avatar asked Jan 19 '17 01:01

Feeco


1 Answers

 markList.stream().collect(
     groupingBy(
         Mark::getSubject,
         () -> new EnumMap<Subject, Integer>(Subject.class),
         summingInt(Mark::getValue)));
like image 56
Louis Wasserman Avatar answered Sep 22 '22 16:09

Louis Wasserman