TreeMap replace(K, V) in Java

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

Syntax:

String java.util.TreeMap.replace(K key, V value)

This method takes two arguments. This method replaces the entry for the specified key only if it is currently mapped to some value.

Parameters: Two parameters are required or this method.

key: key with which the specified value is associated.

value: value to be associated with the specified key.

Returns: the previous value associated with the specified key, or null if there was no mapping for the key.

Exceptions: NA

Approach

Java

import java.util.TreeMap;

public class TreeMapreplace {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer key = 11;
        String value = "World";

        System.out.println(treeMap.replace(key, value));

    }
}

Output:

Java


No comments:

Post a Comment