HashMap computeIfAbsent(K, Function) in Java

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

Syntax:

V java.util.HashMap.computeIfAbsent(K key, Function<? super String, ? extends Integer> 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 mappingfunction 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.HashMap;
import java.util.function.Function;

public class HashMapcomputeIfAbsent {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap =
new HashMap<String, Integer>();

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

        String key = "123";
        Function<? super String, ?
extends Integer> mappingFunction = k -> 1;

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

    }
}

Output:

1

No comments:

Post a Comment