如何在 Java 中迭代 HashMap 值时替换它们 [英] How to replace HashMap Values while iterating over them in Java

查看:30
本文介绍了如何在 Java 中迭代 HashMap 值时替换它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Runnable 每秒自动从玩家的冷却时间中减去 20,但我不知道如何在迭代时替换值的值.如何让它更新每个键的值?

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 8:

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

<小时>

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

这篇关于如何在 Java 中迭代 HashMap 值时替换它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆