合并两张地图的最佳做法是什么?

Sam*_*oos 3 java iteration collections merge map

如何将新地图添加到现有地图.地图具有相同的类型Map<String, Integer>.如果新地图中的密钥存在于旧地图中,则应添加值.

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?
Run Code Online (Sandbox Code Playgroud)

Ale*_* C. 5

通过添加,我假设您要添加整数值,而不是创建一个Map<String, List<Integer>>.

在java 7之前,你必须迭代@laune显示(+1给他).否则使用java 8,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}
Run Code Online (Sandbox Code Playgroud)

它的作用是,对于每个键值对,它合并键(如果它还没有newMap,它只是创建一个新的键值对,否则它通过添加两个整数来更新现有键的先前值保持)

也许你应该考虑使用a Map<String, Long>来避免在添加两个整数时溢出.