Java 合并两个地图的最佳做法是什么

Java 合并两个地图的最佳做法是什么,java,collections,map,merge,iteration,Java,Collections,Map,Merge,Iteration,如何将新地图添加到现有地图。这些地图具有相同的类型Map。如果新映射中的键存在于旧映射中,则应添加值 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

如何将新地图添加到现有地图。这些地图具有相同的类型
Map
。如果新映射中的键存在于旧映射中,则应添加值

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 oldMap=newtreemap();
Map newMap=newtreemap();
//添加的数据
//现在,迭代这些映射以添加两者的值的最佳方法是什么?
for(Map.Entry:newMap.entrySet()){
//从newMap获取键和值并插入/添加到oldMap
整数oldVal=oldMap.get(entry.getKey());
如果(oldVal==null){
oldVal=entry.getValue();
}否则{
oldVal+=entry.getValue();
}
newMap.put(entry.getKey(),oldVal);
}

希望这就是您所说的添加的意思,我假设您想要添加整数值,而不是创建
映射

在Java7之前,您必须像@laune显示的那样进行迭代(+1)。否则,在Java8中,地图上有一个合并方法。所以你可以这样做:

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}
Map oldMap=newtreemap();
Map newMap=newtreemap();
旧地图,放在上面(“1”,10);
旧地图,放在上面(“2”,5);
newMap.put(“1”,7);
forEach((k,v)->newMap.merge(k,v,(a,b)->a+b));
System.out.println(newMap)//{1=17, 2=5}
它所做的是,对于每个键值对,它合并键(如果它还不在
newMap
,它只创建一个新的键值对,否则它通过添加两个整数来更新现有键保留的先前值)

也可以考虑在添加两个整数时使用<代码> map <代码>避免溢出。

也见
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}