Adding values ​​of two cards when the same key

Looking for a standard way of library functions in Java to add values ​​to 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 encoded in several lines. I also know that functional programming is great for this. I just wander around if there is a standard function or syntax that people use there.

Something like (but probably more general):

  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; } 

+6
source share
3 answers

I think what you are doing is wonderful. I can think of it using MultiMap . You can add all your elements to the multimap, and then run the summation function over all values ​​for each key at the end.

+1
source

An alternative that does pretty much the same using Java 8's 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 you use Java 8, you can also pass the keys and make them 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))); 
+3
source

Here is the version that allows you to combine any number of Maps :

 public static Map<String, Integer> addKeys(Map<String, Integer>... maps) { Set<String> keys = new HashSet<String>(); for (Map<String, Integer> map : maps) keys.addAll(map.keySet()); Map<String, Integer> result = new HashMap<String, Integer>(); for (String key : keys) { Integer value = 0; for (Map<String, Integer> map : maps) if (map.containsKey(key)) value += map.get(key); result.put(key, value); } return result; } 

Using:

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

Ouptut:

 {b=2, c=3, a=3} 

Unfortunately, this is not possible, as far as I can see, to create a generic method:

  public static <K, V extends Number> Map<K, V> addKeys(Class<V> cls, Map<K, V>... maps); 

Because the Number class does not support the + operator. It seems to me a little silly ...

0
source

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


All Articles