将两个Map 相加的最佳方法是什么?

我有以下地图。

Map map1= new HashMap(){{ put("no1","123"); put("no2","5434"); put("no5","234");}}; Map map1 = new HashMap(){{ put("no1","523"); put("no2","234"); put("no3","234");}}; sum(map1, map2); 

我想加入他们,总结类似的键值。 什么是使用java 7或guava库的最好方法?

预期产出

 Map output = { { "no1" ,"646"}, { "no2", "5668"}, {"no5","234"}, {"no3","234" } } 

 private static Map sum(Map map1, Map map2) { Map result = new HashMap(); result.putAll(map1); for (String key : map2.keySet()) { String value = result.get(key); if (value != null) { Integer newValue = Integer.valueOf(value) + Integer.valueOf(map2.get(key)); result.put(key, newValue.toString()); } else { result.put(key, map2.get(key)); } } return result; } 

试试这个

  Map> map3 = new HashMap>(); for (Entry e : map1.entrySet()) { List list = new ArrayList(); list.add(e.getValue()); String v2 = map2.remove(e.getKey()); if (v2 != null) { list.add(v2); } map3.put(e.getKey(), list); } for (Entry e : map2.entrySet()) { map3.put(e.getKey(), new ArrayList(Arrays.asList(e.getValue()))); } 

Java 8引入了Map.merge(K,V,BiFunction) ,这使得这很容易,如果不是特别简洁:

 Map result = new HashMap<>(map1); //or just merge into map1 if mutating it is okay map2.forEach((k, v) -> result.merge(k, v, (a, b) -> Integer.toString(Integer.parseInt(a) + Integer.parseInt(b)))); 

如果你反复这样做,你将会解析并创建很多字符串。 如果你一次只生成一个地图,你最好保持一个字符串列表,只解析和求和一次。

 Map> deferredSum = new HashMap<>(); //for each map mapN.forEach((k, v) -> deferredSum.computeIfAbsent(k, x -> new ArrayList()).add(v)); //when you're done Map result = new HashMap<>(); deferredSum.forEach((k, v) -> result.put(k, Long.toString(v.stream().mapToInt(Integer::parseInt).sum()))); 

如果这个求和是一个常见的操作,请考虑使用Integer作为您的值类型是否更有意义; 在这种情况下,您可以使用Integer::sum作为合并函数,并且不再需要维护延迟总和列表。

试试这个

  Map map1= new HashMap(){{ put("no1","123"); put("no2","5434"); put("no5","234");}}; Map map2 = new HashMap(){{ put("no1","523"); put("no2","234"); put("no3","234");}}; Map newMap=map1; for(String a:map2.keySet()){ if(newMap.keySet().contains(a)){ newMap.put(a,""+(Integer.parseInt(newMap.get(a))+Integer.parseInt(map2.get(a)))); } else{ newMap.put(a,map2.get(a)); } } for(String k : newMap.keySet()){ System.out.println("key : "+ k + " value : " + newMap.get(k)); }