EnumMap getOrDefault(Object, V) in Java

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

Syntax:

String java.util.Map.getOrDefault(Object key, V defaultValue)

This method takes two arguments. This method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Parameters: Two parameters are required for this method.

key: the key whose associated value is to be returned.

defaultValue: the default mapping of the key.

Returns: the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Throws:

1. ClassCastException - if the key is of an inappropriate type for this map.

2. NullPointerException - if the specified key is null and this map does not permit null keys.

Approach 1: When no exception

Java

import java.util.EnumMap;

public class EnumMapgetOrDefault {

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

    public static void main(String[] args) {

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

        enumMap.put(Colour.RED, "Red");
        enumMap.put(Colour.GREEN, "Green");

        enumMap.put(Colour.YELLOW, "Yellow");
        enumMap.put(Colour.ORANGE, "Orange");

        System.out.println(enumMap.getOrDefault(Colour.RED,
"Hello"));

    }
}

Output:

Red

No comments:

Post a Comment