且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将所有的Java hashMap内容放在一起,但不能替换现有的键和值?

更新时间:2022-12-12 20:24:32

看起来你愿意创建一个临时 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);

这里,补丁是你的地图正在添加目标地图。

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);