合并两张地图的最佳做法是什么
如何将新地图添加到现有地图.这些地图具有相同的类型 Map
.如果新地图的键存在于旧地图中,则应添加值.
How can I add a new map to existing map. The maps have the same type Map<String, Integer>
. If the key from new map exists in the old map the values should be added.
Map<String, Integer> oldMap = new TreeMap<>();
Map<String, Integer> newMap = new TreeMap<>();
//Data added
//Now what is the best way to iterate these maps to add the values from both?
推荐答案
通过添加,我假设您想要添加整数值,而不是创建 Map
.
By add, I assume you want to add the integer values, not create a Map<String, List<Integer>>
.
在 java 7 之前,您必须按照@laune 显示的那样进行迭代(对他+1).否则使用 java 8,Map 上有一个合并方法.所以你可以这样做:
Before java 7, you'll have to iterate as @laune showed (+1 to him). Otherwise with java 8, there is a merge method on Map. So you could do it like this:
Map<String, Integer> oldMap = new TreeMap<>();
Map<String, Integer> newMap = new TreeMap<>();
oldMap.put("1", 10);
oldMap.put("2", 5);
newMap.put("1", 7);
oldMap.forEach((k, v) -> newMap.merge(k, v, (a, b) -> a + b));
System.out.println(newMap); //{1=17, 2=5}
它所做的是对于每个键值对,它合并键(如果它还没有在 newMap
中,它只是创建一个新的键值对,否则它会更新之前的值通过添加两个整数来保持现有密钥)
What it does is that for each key-value pair, it merges the key (if it's not yet in newMap
, it simply creates a new key-value pair, otherwise it updates the previous value hold by the existing key by adding the two Integers)
另外,也许您应该考虑使用 Map<String, Long>
以避免两个整数相加时溢出.
Also maybe you should consider using a Map<String, Long>
to avoid overflow when adding two integers.
相关文章