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

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

    ı improve Lucas Ross's code. in stead of enter map by one by in function ı give all maps one times to function with arraylist of hashmap like that

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

    }

    it works too. thanks to everbody

提交回复
热议问题