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

前端 未结 8 1561
清歌不尽
清歌不尽 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:39

    Assume that you have many HashMaps: HashMap map1, map2, map3;

    Then you can use Java 8 streams:

    List> mapList = Arrays.asList(map1, map2, map3);
    
    Map combinedMap = mapList.stream()
            .flatMap(map -> map.entrySet().stream())
            .collect(Collectors.groupingBy(Entry::getKey,
                    Collectors.summingInt(Entry::getValue)));
    

提交回复
热议问题