Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a Java HashMap with new Map

Tags:

java

hashmap

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?

like image 408
Yashwanth Reddy Avatar asked Aug 16 '26 14:08

Yashwanth Reddy


1 Answers

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

finalMap.putAll(currentDataMap)
like image 82
Mureinik Avatar answered Aug 18 '26 04:08

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!