使用 Java 8 合并两个地图

2022-01-22 00:00:00 java java-stream

我有两张这样的地图:

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

相关文章