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?
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)));
                        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)
               )
      );
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With