TreeMap putIfAbsent(K, V) in Java

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

Syntax:

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

This method takes two arguments. If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

Parameters: One parameter is required for this method.

key: key with which the specified value is to be 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 TreeMapputIfAbsent {
    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 = 10;

        String value = "World";

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

    }
}

Output:

null


No comments:

Post a Comment