Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

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 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.

1 Answer

0 votes
by (46k points)

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 which is not Primitive data types, you only need to take it out, concoct it, no need to insert it back within the hashmap.

Related questions

0 votes
1 answer
asked Aug 26, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
asked Aug 13, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 27, 2019 in Java by Ritik (3.5k points)

Browse Categories

...