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 ...
source share