TreeMap computeIfPresent(K, BiFunction) in Java

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

Syntax:

String java.util.TreeMap.computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

This method takes two arguments. If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

Note: If the remapping function returns null, the mapping is removed.

Parameters: Two parameters are required for this method.

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

remappingFunction: the remapping function to compute a value.

Returns: the new value associated with the specified key, or null if none

Throws:

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

Approach

Java

import java.util.TreeMap;
import java.util.function.BiFunction;

public class TreeMapcomputeIfPresent {
    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;

        BiFunction<? super Integer, ? super String,
? extends String> remappingFunction = (a, b) -> a + b;

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

Output:

2Hello


No comments:

Post a Comment