如何将所有Java的hashMap内容放在一起,而不是替换现有的键和值?(How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?)
我需要将所有的键和值从一个A HashMap复制到另一个B上,而不是替换现有的键和值。
最好的方法是什么?
我在想,而不是迭代keySet和checkig是否存在,我会的
Map temp = new HashMap(); // generic later temp.putAll(Amap); A.clear(); A.putAll(Bmap); A.putAll(temp);I need to copy all keys and values from one A HashMap onto another one B, but not to replace existing keys and values.
Whats the best way to do that?
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 ,所以我会这样做:
Map tmp = new HashMap(patch); tmp.keySet().removeAll(target.keySet()); target.putAll(tmp);在这里, patch是要添加到target地图的地图。
感谢Louis Wasserman,这是一个利用Java 8中新方法的版本:
patch.forEach(target::putIfAbsent);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);Here, patch is the map that you are adding to the target map.
Thanks to Louis Wasserman, here's a version that takes advantage of the new methods in Java 8:
patch.forEach(target::putIfAbsent);更多推荐
发布评论