How to update a value, given a key in a java hashmap?

Suppose we have a HashMap<String, Integer> in Java.

How do I update (increment) the integer-value of the string-key for each existence of the string I find?

One could remove and reenter the pair, but overhead would be a concern.
Another way would be to just put the new pair and the old one would be replaced.

In the latter case, what happens if there is a hashcode collision with a new key I am trying to insert? The correct behavior for a hashtable would be to assign a different place for it, or make a list out of it in the current bucket.


map.put(key, map.get(key) + 1);

should be fine. It will update the value for the existing mapping. Note that this uses auto-boxing.


Java 8 way:

You can use computeIfPresent method and supply it a mapping function, which will be called to compute a new value based on existing one.

For example,

Map<String, Integer> words = new HashMap<>();
words.put("hello", 3);
words.put("world", 4);
words.computeIfPresent("hello", (k, v) -> v + 1);
System.out.println(words.get("hello"));

Alternatevely, you could use merge method, where 1 is the default value and function increments existing value by 1:

words.merge("hello", 1, Integer::sum);

In addition, there is a bunch of other useful methods, such as putIfAbsent , getOrDefault , forEach , etc.


hashmap.put(key, hashmap.get(key) + 1);

方法put将替换现有密钥的值,并在不存在时创建它。

链接地址: http://www.djcxy.com/p/16406.html

上一篇: linkedhashmap,hashmap,map和hashtable之间的区别

下一篇: 如何更新一个值,给定一个java hashmap中的键?