Java HashMap replace() Method

Java HashMap Java HashMap

The replace() method replaces the value corresponding to the specified key in the hashMap.

The syntax of the replace() method is:

hashmap.replace(K key, V newValue)
或
hashmap.replace(K key, V oldValue, V newValue)

Note:hashmap is an object of the HashMap class.

Parameter details:

  • key - the key
  • oldValue - the old value
  • newValue - the new value

Return Value

If oldValue is not present, replace the value corresponding to key and return the old value corresponding to key; if oldValue is present, return true upon successful replacement; if key does not exist, return null.

Example

The following example demonstrates the use of the replace() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Replace the mapping with key 2
        String value = sites.replace(2, "Wiki");

        System.out.println("Replaced Value: " + value);
        System.out.println("Updated HashMap: " + sites);
    }
}

Executing the above program produces the following output:

Replaced Value: Example
Updated HashMap: {1=Google, 2=Wiki, 3=Taobao}

HashMap replace() method with old value:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Replace the mapping {1 = Google}; perform the replacement
        sites.replace(1, "Google", "Wiki");  // Returns true
        // The mapping {2 = Weibo} does not exist, so no operation is performed
        sites.replace(2, "Weibo", "Zhihu");  // Returns false
        System.out.println("sites after replace():\n" + sites);
    }
}

Executing the above program produces the following output:

sites HashMap: {1=Google, 2=Example, 3=Taobao}
sites after replace():
{1=Wiki, 2=Example, 3=Taobao}

Java HashMap Java HashMap

Other extensions