使用 Java 8 合并两个地图 [英] Merge two maps with Java 8

查看:19
本文介绍了使用 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:

  1. 如果 map1.place 不在 map2.place 中,那么我将条目添加到 map3.
  2. 如果 map2.place 不在 map1.place 中,则相同,我将条目添加到 map3.
  3. 如果 map1.placemap2.place 中,那么我添加这个条目:
  1. If map1.place is not in map2.place, then I add the entry to map3.
  2. same if map2.place is not in map1.place, I add the entry to map3.
  3. if map1.place is in map2.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

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

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