How to replace HashMap Values while iterating over them in Java

假如想象 提交于 2019-11-30 02:38:43

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

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.

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. There are methods on Map to do both of these things. Personally, I would iterate through each 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 ? 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!