Java – Change the value of a key in a HashMap

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. If we provide a non existing key, the current mapping will be left unchanged.

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}

This code creates a Map object with four entries, and then updates the value of one of the entries. The Map interface is used to store and manage keyvalue pairs

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!

If you would like to learn more on how to update the key in a HashMap in Java, then you should check out this tutorial Java – Update the Key in a HashMap. 

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *