简体   繁体   English

如何在Java中迭代HashMap值时替换它们

[英]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. 我使用Runnable每秒从玩家冷却时间自动减去20,但我不知道如何在迭代它时替换值的值。 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: 使用Java 8:

map.replaceAll((k, v) -> v - 20);

Using Java 7 or older: 使用Java 7或更早版本:

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

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. 好吧,你不能通过遍历Map的一组值来实现它(正如你现在所做的那样),因为如果你这样做,那么你没有引用键,如果你没有引用键,那么您无法更新地图中的条目,因为您无法找到与刚刚更新的值相关联的键。

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 . 使用Maps时,您有两个这样的更新选项,遍历Map中的每个Map.Entry<K,V> ,或者您可以遍历键Set There are methods on Map to do both of these things. Map上有一些方法可以完成这两件事。 Personally, I would iterate through each Map.Entry<K,V> . 就个人而言,我会迭代每个Map.Entry<K,V>

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

Why not iterate over the Map.Entry objects ? 为什么不迭代Map.Entry对象? 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. 每个Entry都会为您提供密钥和值,您无需在Map上执行额外的get()来获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM