Merge two maps with Java 8

java, java-stream

Solution

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))
);

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

Problem

I have two maps like this: ``` map1 = new Map<String, MyObject>(); map2 = new Map<String, MyObject>(); MyObject { Integer mark1; Integer mark2; } ``` What I want to do to is to merge the two maps into a `map3` `<String, MyObject>` like this: - If `map1.place` is not in `map2.place`, then I add the entry to `map3`. - same if `map2.place` is not in `map1.place`, I add the entry to `map3`. - if `map1.place` is in `map2.place`, then I add this entry: - `map1.place, (map1.mark1, map2.mark2)` I have read about `flatMap`, but I really have a hard time using it. Any clue how to do this?

Original source

Related problems