Hashtable computeIfAbsent(K, Function) in Java

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

Syntax:

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

public class HashtablecomputeIfAbsent {
    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";
        Function<? super String, ? extends Integer>
mappingFunction = k -> 1;

        System.out.println(hashtable.computeIfAbsent(key,
mappingFunction));

    }
}

Output:

1


No comments:

Post a Comment