如何将所有的Java hashMap内容放在一起,但不能替换现有的键和值? [英] How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

查看:95
本文介绍了如何将所有的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.

最好的方法是什么那么?

Whats the best way to do that?

我正在思考,而是迭代keySet和checkig是否存在,我会

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

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

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 hashMap内容放在一起,但不能替换现有的键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆