How to update a value, given a key in a hashmap?
To update the value associated with a key in a HashMap in Java, you can use the put()
method.
Here's an example of how to use the put()
method to update the value for a given key:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
// update the value for the "apple" key
map.put("apple", 3);
This will update the value for the "apple" key from 1 to 3.
If the key does not exist in the map, the put()
method will add a new key-value pair to the map. For example:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
// add a new key-value pair to the map
map.put("cherry", 3);
This will add a new key-value pair with the key "cherry" and the value 3 to the map.
You can also use the put()
method to update the value for a key and return the previous value associated with the key. This can be useful if you want to know what the previous value was, or if you want to perform some operation based on the previous value.
Here's an example of how to use the put()
method to update the value for a key and return the previous value:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
// update the value for the "apple" key and get the previous value
int prev = map.put("apple", 3);
In this example, the variable prev
will be assigned the value 1, which was the previous value for the "apple" key.
Keep in mind that the put()
method may throw a NullPointerException
if you try to use it with a null
key or value. You can use the containsKey()
and containsValue()
methods to check whether a key or value is present in the map before using the put()
method.