Search code examples
javahashmaptreemap

How can I not overwrite values via putAll() but instead add to the current value?


Suppose I have two hash maps:

HashMap <String, Integer> h1;
h1.put("hi", 30);
h1.put("hi2",20);
h1.put("hi3",10);
h1.put("hi4",20);


HashMap <String, Integer> h2;
h2.put("hi", 20);
h2.put("hi2", 20);
h2.put("hi3", 20);
h2.put("hi4", 20);

My question is, if I do the following

h2.putAll(h1);

How could I update the values of h2 to be the sum, instead of just overwriting it? That is I want

[{"hi"=50}]
[{"hi2"=40}]
[{"hi3"=30}]
[{"hi4"=40}]

Instead of this

[{"hi"=30}]
[{"hi2"=20}]
[{"hi3"=10}]
[{"hi4"=20}]

Note: no functional constructs (including lambdas) and external libraries are allowed


Solution

  • You can use merge method for that:

        h1.forEach((key, value) -> h2.merge( key, value, Integer::sum));
        System.out.println(h2);
    

    The old fashion way:

        for(String key : h1.keySet()){
            Integer v1 = h1.get(key);
            Integer v2 = h2.get(key);
            h2.put(key, (v2 == null) ? v1 : v1 + v2);
        }
        System.out.println(h2);