Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace HashMap Values while iterating over them in Java

I am using a Runnable to automatically subtract 20 from a players cooldown every second, but I have no idea how to replace the value of a value as I iterate through it. How can I have it update the value of each key?

public class CoolDownTimer implements Runnable {     @Override     public void run() {         for (Long l : playerCooldowns.values()) {             l = l - 20;             playerCooldowns.put(Key???, l);         }     }  } 
like image 280
Zach Sugano Avatar asked Jun 12 '12 08:06

Zach Sugano


People also ask

Can we add a new entry to HashMap while iterating?

How to add new entry while iterating? Create a new Map<String, String> foo instance and set the desired values there. At the end of your process, assign this map to your old map by using map = foo; .

How do you replace an element in a HashMap in Java?

replace() Return Values The HashMap replace() method replaces the mapping and returns: the previous value associated with the specified key, if the optional parameter oldValue is not present. true , if the optional parameter oldValue is present.

How do you remove a mapping while iterating over HashMap in Java?

You should always use Iterator's remove() method to remove any mapping from the map while iterating over it to avoid any error.


1 Answers

Using Java 8:

map.replaceAll((k, v) -> v - 20); 

Using Java 7 or older:

You can iterate over the entries and update the values as follows:

for (Map.Entry<Key, Long> entry : playerCooldowns.entrySet()) {     entry.setValue(entry.getValue() - 20); } 
like image 175
aioobe Avatar answered Nov 05 '22 09:11

aioobe