使用 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
. - 如果
map1.place
在map2.place
中,那么我添加这个条目:
- 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?
推荐答案
这是我认为可行的方法
Map<String, MyObj> map3 = new HashMap<>(map1);
map2.forEach(
(key, value) -> map3.merge(key, value, (v1, v2) -> new MyObject(v1.mark1,v2.mark2))
);
merge 函数负责处理您的场景 3,如果密钥已经存在,它会使用 v1.mark1 和 v2.mark2 创建一个新的 MyObject
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
相关文章