I need to merge two maps in the first one by the following rules:
I need to remove all of the keys from map1
which are not present in the map2
.
I need to update all keys in the map1
with the appropriate values which are present in map2
under these keys.
This is my current code:
Set<String> keysToRemove = new HashSet<>();
map1.forEach((k, v) -> {
if (!map2.containsKey(k)) {
keysToRemove.add(k);
} else {
map1.put(k, map2.get(k));
}
});
for (String k : keysToRemove) {
map1.remove(k);
}
I'm not sure my code is optimal and can be improved. Could you please show the way how to implement this task more effectively?