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);
}
}
}
解决方案
Using Java 8:
map.replaceAll((k, v) -> v - 20);
Using Java 7 or older:
You can iterate over the keys and update the values as follows:
for (Key k : playerCooldowns.keySet()) {
playerCooldowns.put(k, playerCooldowns.get(k) - 20);
}
Or, iterate over the entries as follows:
for (Map.Entry entry : playerCooldowns.entrySet()) {
entry.setValue(entry.getValue() - 20);
}