IdentityHashMap compute(K, BiFunction) in Java

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

Syntax:

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

1. NullPointerException - if the specified key is null and this map does not support null keys, or the remapping function 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.IdentityHashMap;
import java.util.function.BiFunction;

public class IdentityHashMapcompute {

    public static void main(String args[]) {

        IdentityHashMap<String, Integer> identityHashMap =
new IdentityHashMap<String, Integer>();

        identityHashMap.put("Java", 1);
        identityHashMap.put("1", 2);

        String key = "1";

        BiFunction<? super String, ? super Integer,
? extends Integer> remappingFunction = (a,
                b) -> (Integer.parseInt(a) + b);
        identityHashMap.compute(key, remappingFunction);

        System.out.println(identityHashMap);
    }

}

Output:

{Java=1, 1=3}


Approach 2: NullPointerException 

Java

import java.util.IdentityHashMap;
import java.util.function.BiFunction;

public class IdentityHashMapcompute {

    public static void main(String args[]) {

        IdentityHashMap<String, Integer> identityHashMap =
new IdentityHashMap<String, Integer>();

        identityHashMap.put("Java", 1);
        identityHashMap.put("1", 2);

        String key = "1";

        BiFunction<? super String, ? super Integer,
? extends Integer> remappingFunction = null;
        identityHashMap.compute(key, remappingFunction);

        System.out.println(identityHashMap);
    }

}

Output:

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



No comments:

Post a Comment