使用Map#merge 的Java 8 解决方案
从java-8 开始,您可以使用Map#merge(K key, V value, BiFunction remappingFunction),它使用remappingFunction 将一个值合并到Map 中,以防在您想要放入该对的Map 中找到密钥。
// using lambda
newMap.forEach((key, value) -> map.merge(key, value, (oldValue, newValue) -> oldValue));
// using for-loop
for (Map.Entry<Integer, String> entry: newMap.entrySet()) {
map.merge(entry.getKey(), entry.getValue(), (oldValue, newValue) -> oldValue);
}
代码迭代newMap条目(key和value)并通过merge方法将每个条目合并到map中。 remappingFunction 在重复键的情况下被触发,在这种情况下,它表示将使用前(原始)oldValue 值而不是重写。
使用此解决方案,您不需要临时的Map。
让我们举一个例子,将newMap 条目合并到map 中,并在出现重复antry 的情况下保留原始值。
Map<Integer, String> newMap = new HashMap<>();
newMap.put(2, "EVIL VALUE"); // this will NOT be merged into
newMap.put(4, "four"); // this WILL be merged into
newMap.put(5, "five"); // this WILL be merged into
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
newMap.forEach((k, v) -> map.merge(k, v, (oldValue, newValue) -> oldValue));
map.forEach((k, v) -> System.out.println(k + " " + v));
1 one
2 two
3 three
4 four
5 five