Open In App

HashMap replace(key, oldValue, newValue) method in Java with Examples

The replace(K key, V oldValue, V newValue) method of Map interface, implemented by HashMap class is used to replace the old value of the specified key only if the key is previously mapped with the specified old value.

Syntax:

default boolean replace(K key, V oldValue, V newValue)

Parameters: This method accepts three parameters :

Return Value: This method returns boolean value true if old value was replaced, otherwise false.

Exceptions: This method will throw:

Program 1:




// Java program to demonstrate
// replace(K key, V oldValue, V newValue) method
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // Create a HashMap and add some values
        HashMap<String, Integer> map
            = new HashMap<>();
        map.put("a", 100);
        map.put("b", 300);
        map.put("c", 300);
        map.put("d", 400);
  
        // print map details
        System.out.println("HashMap: "
                           + map.toString());
  
        // provide old value, new value for the key
        // which has to replace it's old value, using
        // replace(K key, V oldValue, V newValue) method
        map.replace("b", 300, 200);
  
        // print new mapping
        System.out.println("New HashMap: "
                           + map.toString());
    }
}

Output:
HashMap: {a=100, b=300, c=300, d=400}
New HashMap: {a=100, b=200, c=300, d=400}

Program 2:




// Java program to demonstrate
// replace(K key, V oldValue, V newValue) method
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // Create a HashMap and add some values
        HashMap<String, Integer> map
            = new HashMap<>();
        map.put("a", 100);
        map.put("b", 300);
        map.put("c", 300);
        map.put("d", 400);
  
        // print map details
        System.out.println("HashMap: "
                           + map.toString());
  
        // provide old value, new value for the key
        // which has to replace it's old value,
        // and store the return value in isReplaced using
        // replace(K key, V oldValue, V newValue) method
        boolean isReplaced = map.replace("b", 200, 500);
  
        // print the value of isReplaced
        System.out.println("Old value for 'b' was "
                           + "replaced: " + isReplaced);
  
        // print new mapping
        System.out.println("New HashMap: "
                           + map.toString());
    }
}

Output:
HashMap: {a=100, b=300, c=300, d=400}
Old value for 'b' was replaced: false
New HashMap: {a=100, b=300, c=300, d=400}

References: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#replace-K-V-V-


Article Tags :