how to merge more than one hashmaps also sum the values of same key in java

前端 未结 8 1557
清歌不尽
清歌不尽 2021-02-13 03:03

ı am trying to merge more than one hashmaps also sum the values of same key, ı want to explain my problem with toy example as follows

    HashMap

        
8条回答
  •  星月不相逢
    2021-02-13 03:30

    This is a very nice use case for Java 8 streams. You can concatentate the streams of entries and then collect them in a new map:

    Map combinedMap = Stream.concat(m1.entrySet().stream(), m2.entrySet().stream())
        .collect(Collectors.groupingBy(Map.Entry::getKey,
                 Collectors.summingInt(Map.Entry::getValue)));
    

    There are lots of nice things about this solution, including being able to make it parallel, expanding to as many maps as you want and being able to trivial filter the maps if required. It also does not require the orginal maps to be mutable.

提交回复
热议问题