Java Utility Library

Java HashMap - replace() Method



The java.util.HashMap.replace() method is used to replace the entry for the specified key only if it is currently mapped to some value.

Syntax

public V replace(K key, V value)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key with which the specified value is associated.
value Specify the value to be associated with the specified key.

Return Value

Returns the previous value associated with the specified key, or null if there was no mapping for the key. (A null return can also indicate that the map previously associated null with the key, if the implementation supports null values.)

Exception

NA.

Example:

In the example below, the java.util.HashMap.replace() method is used to replace the entry for the specified key in the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hash map
    HashMap<Integer, String> MyMap = new HashMap<Integer, String>();

    //populating MyMap
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");

    //printing MyMap
    System.out.println("Before replace, MyMap contains: " + MyMap);    

    //replacing the value associated with 101 key
    MyMap.replace(101, "Sam"); 

    //printing MyMap
    System.out.println("After replace, MyMap contains: " + MyMap);  
  }
}

The output of the above code will be:

Before replace, MyMap contains: {101=John, 102=Marry, 103=Kim}
After replace, MyMap contains: {101=Sam, 102=Marry, 103=Kim}

❮ Java.util - HashMap