There are many ways to change the value of a key in HashMap.
In this tutorial, you will learn the three most used ways:
- Using the map.replace() method
- Using the map.put() method
- Using the Java 8 computeIfPresent() method
Change the value of a key a HashMap using the map.replace() method
The map.replace() method replaces the entry for the specified key only if it is currently mapped to some value.
import java.util.*; public class Test { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("New York", "city"); map.put("Japan", "country"); map.put("London", "country"); map.put("Boston", "city"); // update the value of "London" to "city" map.replace("London", "city"); System.out.println(map); } }
Output: {New York=city, Japan=country, London=city, Boston=city}
If we provide a non existing key, the current mapping will be left unchanged.
Update the value of a key in HashMap using the map.put() method
Since the HashMap can only contain unique keys, we can use the map.put() method to update the value for the existing mapping, like in the following example:
public class Test { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("New York", "city"); map.put("Japan", "country"); map.put("London", "country"); map.put("Boston", "city"); // update the value of "London" to "city" map.put("London", "city"); System.out.println(map); } }
Output: {New York=city, Japan=country, London=city, Boston=city}
The newly added key/value pair with the key “London” replaced the existing one.
Change the value using the computeIfPresent() method
We can also use the computeIfPresent() method and supply it with a mapping function, which will be called to compute a new value based on the existing one.
public class Test { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("New York", "city"); map.put("Japan", "country"); map.put("London", "country"); map.put("Boston", "city"); // update the value of "London" to "city" map.computeIfPresent("London", (k, v) -> "city"); System.out.println(map); } }
Output: {New York=city, Japan=country, London=city, Boston=city}
If we provide a non existing key, the current mapping will be left unchanged.
That’s it!
Happy coding!