How to update a value, given a key in a hashmap?
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.
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.
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)
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.