如何将新 map 添加到现有 map 。这些 map 具有相同的类型 Map<String, Integer>
.如果新 map 中的键存在于旧 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<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}
它所做的是对于每个键值对,它合并键(如果它还不在 newMap
中,它只是创建一个新的键值对,否则它更新现有键持有的先前值通过添加两个整数)
也许你应该考虑使用 Map<String, Long>
以避免在添加两个整数时溢出。
关于java - 合并两张 map 的最佳做法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27335073/