Merge two maps with Java 8

后端 未结 5 729
北荒
北荒 2020-12-06 17:04

I have two maps like this:

map1 = new Map();
map2 = new Map();

MyObject {
   Integer mark1;
   Integer mark2         


        
5条回答
  •  时光说笑
    2020-12-06 17:16

    Here is what I think would work

    Map map3 = new HashMap<>(map1);
    map2.forEach(
        (key, value) -> map3.merge(key, value, (v1, v2) -> new MyObject(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

提交回复
热议问题