本文介绍了如何在Java中迭代HashMap值时进行替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在使用一个Runnable自动从玩家冷却时间中减去20,但我不知道如何在遍历它时替换值的值。 public class CoolDownTimer implements Runnable { @Override $ b我怎样才能让它更新每个键的值? $ b public void run(){ for(Long l:playerCooldowns.values()){l = l - 20; playerCooldowns.put(Key ???,l); $ b 解决使用Java 8: map.replaceAll((k, v)→v-20); 使用Java 7或更早版本: 您可以迭代键并更新值,如下所示: playerCooldowns.put(k,playerCooldowns.get(k) - 20); code> } 或者,迭代条目如下:$ b $ (Map.Entry< Key,Long>条目:playerCooldowns.entrySet()){ entry.setValue(entry.getValue() - b 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); } }} 解决方案 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<Key, Long> entry : playerCooldowns.entrySet()) { entry.setValue(entry.getValue() - 20);} 这篇关于如何在Java中迭代HashMap值时进行替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 05-31 23:53