How to easily sum two hashMap <String, Integer>?

I have two HashMap<String,Integer>

How can I easily summarize them?

Will the value for string "a" be the sum (the value from the value Map1 + from Map2)?

I can iterate over each element of Map2 and manually add to Map1.

But thought there might be an easier way?

I prefer summing integers onto one of the cards. Do not create new

+4
source share
3 answers

Since Java 8 Mapcontains a mergemethod that requires

  • ,
  • new meaning
  • , , , ( ).

, :

map2.forEach((k, v) -> map1.merge(k, v, Integer::sum));

map1 map2, , .

DEMO:

Map<String, Integer> m1 = new HashMap<>();
m1.put("a", 1);
m1.put("b", 2);
Map<String, Integer> m2 = new HashMap<>();
m2.put("a", 3);
m2.put("c", 10);

System.out.println(m1);
System.out.println(m2);

//iterate over second map and merge its elements into map 1 using 
//same key and sum of values
m2.forEach((k, v) -> m1.merge(k, v, Integer::sum));

System.out.println("===========");
System.out.println(m1);

:

{a=1, b=2}
{a=3, c=10}
===========
{a=4, b=2, c=10}
+10

, . .

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class HashMapSum {

    public static void main(String[] args) {
        Map<String, Integer> map1 = new HashMap<String, Integer>();
        map1.put("a", 1);
        map1.put("b", 2);
        map1.put("c", 3);

        Map<String, Integer> map2 = new HashMap<String, Integer>();
        map2.put("a", 4);
        map2.put("b", 5);
        map2.put("d", 6);

        Set<String> keySet = new HashSet<String>();
        keySet.addAll(map1.keySet());
        keySet.addAll(map2.keySet());

        Map<String, Integer> map3 = new HashMap<String, Integer>();
        Integer val1, val2;
        for (String key : keySet) {
            val1 = map1.get(key);
            val1 = (val1 == null ? 0 : val1);
            val2 = map2.get(key);
            val2 = (val2 == null ? 0 : val2);
            map3.put(key, val1 + val2);
        }

        System.out.println(map3.toString());
    }
}
+1

Java 8:

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

. Stream<Map.Entry<String, Integer> , Map " " .

-

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

Source: https://habr.com/ru/post/1615317/


All Articles