TreeMap computeIfAbsent(K, Function) in Java

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

Syntax:

String java.util.TreeMap.computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

This method takes two arguments. If the specified key is not already associated with a value (or is mapped to null), attempt to compute its value using the given mapping function and enter it into this map unless null.

Parameters: Two parameters are required for this method.

key: key with which the specified value is to be associated.

mappingFunction: the mapping function to compute a value.

Returns: the current (existing or computed) value associated with the specified key, or null if the computed value is null.

Throws:

ConcurrentModificationException - if it is detected that the mapping function modified this map

Approach

Java

import java.util.TreeMap;
import java.util.function.Function;

public class TreeMapcomputeIfAbsent {
    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 = 2;

        Function<? super Integer, ? extends String>
remappingFunction = a -> a.toString();

        System.out.println(treeMap.computeIfAbsent(key,
remappingFunction));
    }
}

Output:

Hello


No comments:

Post a Comment