HashMap replace(K, V, V) in Java

replace(K, V, V): This method is available in java.util.HashMap class of Java.

Syntax:

boolean java.util.HashMap.replace(K key, V oldValue, V newValue)

This method takes three arguments. This method replaces the entry for the specified key only if currently mapped to the specified value.

Parameters: Three parameters are required for this method.

key: key with which the specified value is associated.

oldValue: value expected to be associated with the specified key.

newValue: value to be associated with the specified key.

Returns: true if the value was replaced.

Exceptions: NA

Approach

Java

import java.util.HashMap;

public class HashMapreplace2 {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap =
new HashMap<String, Integer>();

        hashMap.put("Hello", 1);
        hashMap.put("World", 2);

        String key = "Hello";
        Integer oldValue = 1, newValue = 10;
        hashMap.replace(key, oldValue, newValue);

        System.out.println(hashMap);

    }
}

Output:

{Hello=10, World=2}


No comments:

Post a Comment