EnumMap compute(K,V) in Java

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

Syntax:

String java.util.Map.compute(K key, BiFunction<? super K, ? super V, ? extends V> remapping function)

This method takes two arguments. This method Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

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(optional).

Approach 1: When no exception

Java

import java.util.EnumMap;

public class EnumMapcompute {

    public enum Colour {
        RED, GREEN, YELLOW, ORANGE
    };

    public static void main(String[] args) {

        EnumMap<Colour, String> enumMap =
new EnumMap<Colour, String>(Colour.class);

        System.out.println(enumMap.compute(Colour.RED,
(k, v) -> (v == null) ? "Hello" : v.concat("Hello")));
    }
}

Output:

Hello


Approach 2: NullPointerException

Java

import java.util.EnumMap;

public class EnumMapcompute {

    public enum Colour {
        RED, GREEN, YELLOW, ORANGE
    };

    public static void main(String[] args) {

        EnumMap<Colour, String> enumMap =
new EnumMap<Colour, String>(Colour.class);

        System.out.println(enumMap.compute(Colour.RED, null));
    }
}

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