Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify value of map with forEach

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?

like image 583
nimo23 Avatar asked Sep 06 '17 18:09

nimo23


People also ask

Can we modify map while iterating?

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.

How do you change a value in a Java map?

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.

How do you set a value on a map?

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.


1 Answers

This is the job for Map#replaceAll:

mymap.replaceAll((k, v) -> v + " hello");
like image 190
Misha Avatar answered Sep 19 '22 06:09

Misha