How to replace HashMap Values while iterating over them in Java

JavaHashmapRunnable

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

Well, you can't do it by iterating over the set of values in the Map (as you are doing now), because if you do that then you have no reference to the keys, and if you have no reference to the keys, then you can't update the entries in the map, because you have no way of finding out which key was associated with the value you just updated.

When working with Maps, you have two options for updates like this, iterate through each Map.Entry<K,V> in the Map, or you can iterate through the key Set. There are methods on Map to do both of these things. Personally, I would iterate through each Map.Entry<K,V>.

for (Map.Entry<String, Long> entry : playerCooldowns.entrySet()) {
    entry.setValue(entry.getValue() - 20);
}

Solution 3 - Java

Why not iterate over the Map.Entry objects ? Each Entry will give you the key and value and you don't have to perform an additional get() on the Map to get a value.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZach SuganoView Question on Stackoverflow
Solution 1 - JavaaioobeView Answer on Stackoverflow
Solution 2 - JavaJonView Answer on Stackoverflow
Solution 3 - JavaBrian AgnewView Answer on Stackoverflow