I have a HashMap and want to change the value (which is a string) by appending another string "hello".
HashMap<User, String> all = new HashMap<>();
mymap.forEach((k, v) -> v = v + " hello");
However, it does not work, "mymap" is unchanged. What is wrong?
It is not allowed to modify a map in Java while iterating over it to avoid non-deterministic behavior at a later stage. For example, the following code example throws a java. util. ConcurrentModificationException since the remove() method of the Map interface is called during iteration.
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.
put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
This is the job for Map#replaceAll
:
mymap.replaceAll((k, v) -> v + " hello");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With