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); } } }
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; .
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.
You should always use Iterator's remove() method to remove any mapping from the map while iterating over it to avoid any error.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With