如何在Java中迭代HashMap值时进行替换 [英] How to replace HashMap Values while iterating over them in Java
问题描述
public class CoolDownTimer implements Runnable {
@Override $ b我怎样才能让它更新每个键的值? $ b public void run(){
for(Long l:playerCooldowns.values()){
l = l - 20;
playerCooldowns.put(Key ???,l);
$ b
map.replaceAll((k, v)→v-20);
使用Java 7或更早版本: 您可以迭代键并更新值,如下所示: 或者,迭代条目如下:$ b $ (Map.Entry< Key,Long>条目:playerCooldowns.entrySet()){ 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?
Using Java 8:
Using Java 7 or older: You can iterate over the keys and update the values as follows: Or, iterate over the entries as follows:
这篇关于如何在Java中迭代HashMap值时进行替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
< (Key k:playerCooldowns.keySet()){
playerCooldowns.put(k,playerCooldowns.get(k) - 20); code>
}
entry.setValue(entry.getValue() - b
20);
}
public class CoolDownTimer implements Runnable {
@Override
public void run() {
for (Long l : playerCooldowns.values()) {
l = l - 20;
playerCooldowns.put(Key???, l);
}
}
}
map.replaceAll((k, v) -> v - 20);
for (Key k : playerCooldowns.keySet()) {
playerCooldowns.put(k, playerCooldowns.get(k) - 20);
}
for (Map.Entry<Key, Long> entry : playerCooldowns.entrySet()) {
entry.setValue(entry.getValue() - 20);
}