如何将所有Java的hashMap内容放在一起,而不是替换现有的键和值?(How to putAll on Java hashMap contents of one to another, but n

编程入门 行业动态 更新时间:2024-10-26 18:21:19
如何将所有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);

更多推荐

本文发布于:2023-07-23 02:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226575.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   放在一起   而不是   内容   hashMap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!