Skip to content

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:

java
import java.util.Map;
import java.util.HashMap;

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:

java
import java.util.Map;
import java.util.HashMap;

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:

java
import java.util.Map;
import java.util.HashMap;

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 java.util.HashMap explicitly supports null keys and values. If you need to check whether a key is present before updating, you can use the containsKey() method.

Dual-run preview — compare with live Symfony routes.