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

459    Asked by DrucillaTutt in Java , Asked on Apr 19, 2021

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 re-enter the pair, but the 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.

Answered by Drucilla Tutt

You can use:

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

to update the value for existing mapping.

To learn more about it check this official document by Java.

if there is a hashcode collision with a new key you are trying to insert you need to take it out, make some process, then insert it back. if you hold a value that is not Primitive data types, you only need to take it out, concoct it, no need to insert it back within the hashmap.

So, use java hashmap update value to update a value, given a key in a hashmap?



Your Answer

Interviews

Parent Categories