java - 如何将Java hashMap内容的全部放在另一个上,但不替换现有的键和值? [英] How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?
本文介绍了java - 如何将Java hashMap内容的全部放在另一个上,但不替换现有的键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将一个 A HashMap 中的所有键和值复制到另一个 B 上,而不是替换现有的键和值.
I need to copy all keys and values from one A HashMap onto another one B, but not to replace existing keys and values.
最好的方法是什么?
我想改为迭代 keySet 并检查它是否存在,我会
I was thinking instead iterating the keySet and checkig if it exist or not, I would
Map temp = new HashMap(); // generic later
temp.putAll(Amap);
A.clear();
A.putAll(Bmap);
A.putAll(temp);
推荐答案
看来你愿意创建一个临时的Map
,所以我会这样做:
It looks like you are willing to create a temporary Map
, so I'd do it like this:
Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);
这里,patch
是您要添加到 target
地图的地图.
Here, patch
is the map that you are adding to the target
map.
感谢 Louis Wasserman, 这是一个利用 Java 8 中新方法的版本:
Thanks to Louis Wasserman, here's a version that takes advantage of the new methods in Java 8:
patch.forEach(target::putIfAbsent);
这篇关于java - 如何将Java hashMap内容的全部放在另一个上,但不替换现有的键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文