0 votes
1 view
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 (46.1k 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 (4.1k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 15, 2019 in Java by Nigam (4.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...