Easy Tutorial
❮ Java Object Wait Timeout Arrays Removeall ❯

Java HashMap replace() Method

Java HashMap

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

The syntax for the replace() method is:

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

Note: hashmap is an object of the HashMap class.

Parameter Description:

Return Value

If the oldValue does not exist, it replaces the value associated with the key, returns the old value associated with the key, if the oldValue exists, returns true if the replacement is successful, and if the key does not exist, returns 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&lt;Integer, String> sites = new HashMap<>();

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

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

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

Executing the above program outputs:

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

HashMap replace() method with an old value:

Example

import java.util.HashMap;

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

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        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
        // Mapping {2 = Weibo} does not exist, no operation
        sites.replace(2, "Weibo", "Zhihu");  // returns false
        System.out.println("sites after replace():\n" + sites);
    }
}

Executing the above program outputs:

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

Java HashMap

❮ Java Object Wait Timeout Arrays Removeall ❯