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.
hashmap. put(key, hashmap. get(key) + 1); The method put will replace the value of an existing key and will create it if doesn't exist.
We use the put() method with HashMap when we want to insert a value into the HashMap . And we can also use it to update the value inside the HashMap .
You cannot rename/modify the hashmap key once added. Only way is to delete/remove the key and insert with new key and value pair. Reason : In hashmap internal implementation the Hashmap key modifier marked as final .
When you mutate a key which is already present in the HashMap you break the HashMap .
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. With the help of map.get(key)
we get the value of corresponding key, then you can update with your requirement. Here I am updating to increment value by 1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With