使用Java 8合并两个映射 [英] Merge two maps with Java 8
本文介绍了使用Java 8合并两个映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两张这样的地图:
map1 = new Map<String, MyObject>();
map2 = new Map<String, MyObject>();
MyObject {
Integer mark1;
Integer mark2;
}
我想要做的是将两张地图合并为一个 map3
< String,MyObject>
这样:
What I want to do to is to merge the two maps into a map3
<String, MyObject>
like this:
- 如果
map1.place
不在map2.place
中,那么我添加进入map3
。 - 如果
map2.place
不在map1.place
,我将条目添加到map3
。 - if
map1.place
在map2.place
中,然后我添加此条目:
-
map1.place,(map1.mark1,map2.mark2)
-
- If
map1.place
is not inmap2.place
, then I add the entry tomap3
. - same if
map2.place
is not inmap1.place
, I add the entry tomap3
. - if
map1.place
is inmap2.place
, then I add this entry:map1.place, (map1.mark1, map2.mark2)
我读过关于 flatMap
的信息,但我真的很难用它。
任何线索怎么做?
谢谢!!
I have read about flatMap
, but I really have a hard time using it.
Any clue how to do this?
Thanks!!
推荐答案
以下是我认为可行的方法
Here is what I think would work
Map<String, MyObj> map3 = new HashMap<>(map1);
map2.forEach(
(key, value) -> map3.merge(key, value, (v1, v2) -> new MyObject(v1.mark1,v2.mark2))
);
合并功能正在处理你的场景3,因为如果密钥已经存在,它使用v1.mark1和v2.mark2
The merge function is what is taking care of your scenario 3, in that if the key already exists, it creates a new MyObject with v1.mark1 and v2.mark2
这篇关于使用Java 8合并两个映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文