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;
}
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)));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With