Hashtable computeIfPresent(K, BiFunction) in Java

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

Syntax:

V java.util.Hashtable.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.

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.Hashtable;
import java.util.function.BiFunction;

public class HashtablecomputeIfPresent {
    public static void main(String[] args) {
        Hashtable<String, Integer> hashtable =
new Hashtable<String, Integer>();

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

        String key = "123";
        BiFunction<? super String, ? super Integer,
? extends Integer> remappingFunction =
(a, b) -> Integer.parseInt(a)
                + 12;
        System.out.println(hashtable.computeIfPresent(key,
remappingFunction));

    }
}

Output:

null


No comments:

Post a Comment