Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing map values per each key

Tags:

java

I have the following maps:

{21=0, 22=2, 11=0, 12=0}
{21=3, 22=0, 11=6, 12=3}
{21=6, 22=0, 11=7, 12=0}
{21=5, 22=7, 11=9, 12=1}

The following code returns these maps:

for (Chrom t: obj.getChroms) {
    Map<Integer, Integer> result = t.getExecutionCount();
}

The method getExecutionCount() returns a single map. For the example I have given above, I have four chroms where each chrom will returns a single map.

I would like to sum the values of each key seperately so that the final result will be:

21 = 14
22 = 9
11 = 22
12 = 4

Is it possible to use stream to do that? If not, how can I do that?

like image 582
Adam Amin Avatar asked Dec 03 '22 18:12

Adam Amin


2 Answers

Try this:

    List<Map<Integer, Integer>> maps;

    Map<Integer, Integer> result = maps.stream()
            .map(Map::entrySet)
            .flatMap(Collection::stream)
            .collect(Collectors.groupingBy(
                    Map.Entry::getKey,
                    Collectors.summingInt(Map.Entry::getValue)));
like image 75
talex Avatar answered Dec 25 '22 07:12

talex


You can create Stream of maps and the use flatMap,

Stream.of(map1, map2, map3)
      .flatMap(m -> m.entrySet()
                     .stream())
      .collect(Collectors.groupingBy(
                   Map.Entry::getKey,
                   Collectors.summingInt(Map.Entry::getValue)
               )
      );
like image 30
Vikas Yadav Avatar answered Dec 25 '22 07:12

Vikas Yadav