What is the EnumMap.containsKey() method in Java?

Overview

The containsKey() method of EnumMap is used to check if a value is mapped to the specified key.

Note: EnumMap is similar to Map, except that EnumMap only takes the Enum type as a key. Also, all the keys must be from a single enum type. For further details, refer here.

Syntax


public boolean containsKey(Object key)

Parameters

The key to check is passed as an argument.

Note: EnumMap doesn’t allow null keys, so if we pass null as an argument, we will get false as the result.


Return value

This method returns true if the key has a mapping. Otherwise, it returns false.

Code

The example below shows how to use the containsKey() method.

import java.util.EnumMap;
class ContainsKey {
enum Days{
MON, TUE, WED, THUR, FRI, SAT, SUN
};
public static void main( String args[] ) {
EnumMap<Days, String> map = new EnumMap<>(Days.class);
map.put(Days.MON, "chest");
System.out.println( "The map is" + map);
System.out.println("Checking if the key Days.MON has mapping: "+ map.containsKey(Days.MON));
System.out.println("Checking if the key Days.FRI has mapping: "+ map.containsKey(Days.FRI));
System.out.println("Checking if the key null has mapping: "+ map.containsKey(null));
}
}

Explanation

  • Line 1: We import the EnumMap class.

  • Line 3: We create an enum for days of the week with the name Days.

  • Line 7: We create an EnumMap object with the name map.

  • Line 8: We use the put method to add a mapping {Days.MON="chest"} to the map object.

  • Line 11: We use the containsKey method to check if map has a mapping for the key Days.MON. We get true as a result because the map has a mapping for the key Days.MON.

  • Line 12: We use the containsKey method to check if map has a mapping for the key Days.FRI. We get false as a result because the map does not have mapping for the key Days.FRI.

  • Line 13: We use the containsKey method to check if map has a mapping for the key null. The EnumMap doesn’t allow null keys, so false is returned.