Search code examples
javahashmaprunnable

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

}

Solution

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