合并Java中的两个Maps [英] Merge two Maps of Maps in Java

查看:105
本文介绍了合并Java中的两个Maps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HashMap,而其中又包含一个HashMap,

I have a HashMap which in turn has a HashMap within,

Map<Long, Map<String, Double>> map = new HashMap<>();

对于同一个Long值,我将有多个内部映射,如何确保不替换value字段,而是合并(附加)?

I will have multiple inner maps for the same Long value, how do I make sure that the value field isn't replaced and rather merged (appended)?

此问题与如何将Java hashMap上的内容全部放置到另一个上,而不替换现有的键和值?因为它是关于弦乐图的,所以我迷上了地图的图

This question differs from How to putAll on Java hashMap contents of one to another, but not replace existing keys and values? as it is about a Map of Strings, I'm stuck with a map of maps

例如

Map<Long, Map<String, Double>> map = new HashMap<>();
Map<String, Double> map1 = new HashMap<>();
Map<String, Double> map2 = new HashMap<>();

map1.put("1key1", 1.0);
map1.put("1key2", 2.0);
map1.put("1key3", 3.0);

map2.put("2key1", 4.0);
map2.put("2key2", 5.0);
map2.put("2key3", 6.0);

map.put(222l, map1);
map.put(222l, map2);

应该给我6个键'222'的内部映射条目,而不是3个.

should give me 6 innermap entries for key '222' and not 3.

推荐答案

如果您使用的是Java 8,而不是put,则可以调用

If you are using Java 8, instead of put you can call a merge method:

map.merge(222L, map2, (m1, m2) -> {m1.putAll(m2);return m1;});

如果地图已经具有与给定键相对应的值,则将调用作为第三个参数传递的合并函数,该函数只会将新地图的内容添加到先前存在的地图中.这是完整的代码:

If map already had a value corresponding to given key, the merge function passed as third argument will be called which just adds the content of the new map to the previously existing one. Here's complete code:

Map<Long, Map<String, Double>> map = new HashMap<>();
Map<String, Double> map1 = new HashMap<>();
Map<String, Double> map2 = new HashMap<>();

map1.put("1key1", 1.0);
map1.put("1key2", 2.0);
map1.put("1key3", 3.0);

map2.put("2key1", 4.0);
map2.put("2key2", 5.0);
map2.put("2key3", 6.0);

map.merge(222L, map1, (m1, m2) -> {m1.putAll(m2);return m1;});
map.merge(222L, map2, (m1, m2) -> {m1.putAll(m2);return m1;});
System.out.println(map);

打印所有六个键:

{222={1key2=2.0, 1key3=3.0, 2key3=6.0, 2key1=4.0, 1key1=1.0, 2key2=5.0}}

这篇关于合并Java中的两个Maps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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