Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding the values of two maps when same key

Tags:

java

map

Looking for a standard library function way in Java for adding the values in two maps based on their keys.

Map A: {a=1, b=2}
Map B: {a=2, c=3}

Resulting map:

Map C: {a=3, b=2, c=3}

I know this can be coded in a few lines. I also know functional programming is great for this. I am just wandering if there is a standard function or syntax people use out there.

Something like (but probably more generic than):

 public HashMap<String,Double> addValues(HashMap<String,Double> a, HashMap<String,Double> b) {
    HashMap<String,Double> ret = new HashMap<String,Double>(a);
    for (String s : b.keySet()) {
      if (ret.containsKey(s)) {
        ret.put(s, b.get(s) + ret.get(s));
      } else {
        ret.put(s, b.get(s));
      }
    }
    return ret;
  }

like image 912
Hugo Zaragoza Avatar asked Jul 01 '14 14:07

Hugo Zaragoza


2 Answers

An alternative which does essentially the same thing, using Java 8 new getOrDefault method:

Set<String> keys = new HashSet<> (a.keySet());
keys.addAll(b.keySet());

Map<String, Integer> c = new HashMap<>();
for (String k : keys) {
  c.put(k, a.getOrDefault(k, 0) + b.getOrDefault(k, 0));
}

But if using Java 8, you may as well stream the keys and make it a one liner:

Map<String, Object> c = Stream.concat(a.keySet().stream(), b.keySet().stream())
         .distinct()
         .collect(toMap(k -> k, k -> a.getOrDefault(k, 0) + b.getOrDefault(k, 0)));
like image 128
assylias Avatar answered Oct 10 '22 10:10

assylias


I think what you are doing is just fine. I can think of one other way though, using a MultiMap. You can add all your elements to a multimap and then run a summation function over all the values for each key at the end.

like image 37
noMAD Avatar answered Oct 10 '22 11:10

noMAD