Hashtable compute(K, BiFunction) in Java

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

Syntax:

V java.util.Hashtable.compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

This method takes two arguments. This method attempts to compute a mapping for the specified 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 Hashtablecompute {
    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;
        hashtable.compute(key, remappingFunction);

        System.out.println(hashtable);
    }
}

Output:

{World=2, 123=135, Hello=1}


No comments:

Post a Comment