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

1,050,160

Solution 1

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.

Solution 2

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.

Solution 3

The simplified Java 8 way:

map.put(key, map.getOrDefault(key, 0) + 1);

This uses the method of HashMap that retrieves the value for a key, but if the key can't be retrieved it returns the specified default value (in this case a '0').

This is supported within core Java: HashMap<K,V> getOrDefault(Object key, V defaultValue)

Solution 4

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.

Solution 5

Replace Integer by AtomicInteger and call one of the incrementAndGet/getAndIncrement methods on it.

An alternative is to wrap an int in your own MutableInteger class which has an increment() method, you only have a threadsafety concern to solve yet.

Share:
1,050,160
laertis
Author by

laertis

Just a "wanna be" good programmer..

Updated on July 16, 2022

Comments

  • laertis
    laertis almost 2 years

    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.