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

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

    This method should do it (in Java 5+)

    public static  Map mergeAndAdd(Map... maps) {
        Map result = new HashMap<>();
        for (Map map : maps) {
            for (Map.Entry entry : map.entrySet()) {
                K key = entry.getKey();
                Integer current = result.get(key);
                result.put(key, current == null ? entry.getValue() : entry.getValue() + current);
            }
        }
        return result;
    }
    

提交回复
热议问题