EnumMap computeIfAbsent(K, Function) in Java

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

Syntax:

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

1. NullPointerException - if the specified key is null and this map does not support null keys or the mappingFunction 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.EnumMap;

public class EnumMapcomputeIfAbsent {

    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.computeIfAbsent(Colour.RED,
k -> "Hello"));

    }
}

Output:

Hello


Approach 2: NullPointerException 

Java

import java.util.EnumMap;

public class EnumMapcomputeIfAbsent {

    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.computeIfAbsent(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.computeIfAbsent(Map.java:998)


No comments:

Post a Comment