dardy :
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 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)
I have read about flatMap
, but I really have a hard time using it.
Any clue how to do this?
Thanks!!
Ash :
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
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=452252&siteId=1