HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
keyhowupdatevaluehashmapgiven

Problem

Suppose we have a HashMap 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.

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#4157972, score: 1235

Revisions (0)

No revisions yet.