How to replace HashMap Values while iterating over them in Java

Zach Sugano picture Zach Sugano · Jun 12, 2012 · Viewed 66.1k times · Source

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);
        }
    }

}

Answer

aioobe picture aioobe · Jun 12, 2012

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);
}