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 the specified value.
Syntax
public boolean replace(K key, V oldValue, V newValue)
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. |
oldValue |
Specify value expected to be associated with the specified key. |
newValue |
Specify value to be associated with the specified key. |
Return Value
Returns true if the value was replaced.
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, "John", "Sam"); //replacing the value associated with 102 key //it is not replaced as oldValue is not matching MyMap.replace(102, "Jo", "Peter"); //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