WeakHashMap computeIfPresent(K, BiFunction) in Java

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

Syntax:

Integer java.util.Map.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, attempt 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:

1. NullPointerException - if the specified key is null and this map does not support null keys, or the remappingFunction is null.

2. UnsupportedOperationException - if the put operation is not supported by this map.

3. ClassCastException - if the class of the specified key or value prevents it from being stored in this map.

4. IllegalArgumentException - if some property of the specified key or value prevents it from being stored in this map.

Approach 1: When no exception

Java

import java.util.WeakHashMap;
import java.util.function.BiFunction;

public class WeakHashMapcomputeIfPresent {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        String key = "1";

        BiFunction<? super String, ? super Integer,
? extends Integer> remappingFunction =
(k, v) -> Integer.parseInt(k)
                + v;
        System.out.println(weakHashMap.computeIfPresent(key,
remappingFunction));

    }
}

Output:

null


Approach 2: NullPointerException

Java

import java.util.WeakHashMap;
import java.util.function.BiFunction;

public class WeakHashMapcomputeIfPresent {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        String key = "1";

        BiFunction<? super String, ? super Integer,
? extends Integer> remappingFunction = null;
        System.out.println(weakHashMap.computeIfPresent(key,
remappingFunction));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Map.computeIfPresent(Map.java:1075)


No comments:

Post a Comment