How to update a Java HashMap with new Map

Viewed 41

How can I update a Java HashMap with a new Map? I have a requirement where I have to iteratively update a HashMap with a subsequent new map I get. Update has two parts

  1. Checks if the latest map has any new key not present in the final map and puts them
  2. Updates the keys which are already present in the final map with the latest map values.

Currently, I am doing this

currentDataMap.forEach(finalMap::putIfAbsent);
finalMap.replaceAll(currentDataMap::getOrDefault);

Is there better way or one step way?

1 Answers

It sounds like all you need is a single call to putAll:

finalMap.putAll(currentDataMap)
Related