how to easily sum two hashMap?

后端 未结 3 1919
星月不相逢
星月不相逢 2020-12-18 10:32

I have two HashMap

How can I sum them easily?

Meaning that for String \"a\" the key will be sum of (value from Map1 + valu

3条回答
  •  孤城傲影
    2020-12-18 11:22

    in case you like Java 8:

    Map sum(Map... maps) {
        return Stream.of(maps)    // Stream>
                .map(Map::entrySet)  // Stream>
                .flatMap(Collection::stream) // Stream>
                .collect(Collectors.toMap(Map.Entry::getKey,
                                          Map.Entry::getValue,
                                          Integer::sum));
    }
    

    can sum up arbitrary amounts of maps. It turns the array of maps into a Stream in the first few lines, then collects all the entries into a new Map while supplying a "merge function" in case of duplicate values.

    alternatively something along the lines of

    void addToA(HashMap a, HashMap b) {
        for (Entry entry : b.entrySet()) {
            Integer old = a.get(entry.getKey());
            Integer val = entry.getValue();
            a.put(entry.getKey(), old != null ? old + val : val);
        }
    }
    

提交回复
热议问题