I need to copy all keys and values from one A HashMap onto another one B, but not to replace existing keys and values.
Whats the best way to do that?
I was thinking instead iterating the keySet and checkig if it exist or not, I would
Map temp = new HashMap(); // generic later
temp.putAll(Amap);
A.clear();
A.putAll(Bmap);
A.putAll(temp);
It looks like you are willing to create a temporary
Map, so I’d do it like this:Here,
patchis the map that you are adding to thetargetmap.Thanks to Louis Wasserman, here’s a version that takes advantage of the new methods in Java 8: