Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hashmap

key

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.

like image 797
laertis Avatar asked Nov 11 '10 18:11

laertis


People also ask

How do I change the value of a specific key in a HashMap?

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.

Can you update value in HashMap?

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 .

Can we modify key in 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 .

What happens if we update the key object that is in a HashMap?

When you mutate a key which is already present in the HashMap you break the HashMap .


2 Answers

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.

like image 129
Matthew Flaschen Avatar answered Oct 07 '22 04:10

Matthew Flaschen


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.

like image 44
Konstantin Milyutin Avatar answered Oct 07 '22 06:10

Konstantin Milyutin