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:
EnumMapis similar toMap, except thatEnumMaponly takes theEnumtype as a key. Also, all the keys must be from a singleenumtype. For further details, refer here.
Syntax
public boolean containsKey(Object key)
Parameters
The key to check is passed as an argument.
Note:
EnumMapdoesn’t allownullkeys, so if we passnullas an argument, we will getfalseas 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
EnumMapclass. -
Line 3: We create an
enumfor days of the week with the nameDays. -
Line 7: We create an
EnumMapobject with the namemap. -
Line 8: We use the
putmethod to add a mapping{Days.MON="chest"}to themapobject. -
Line 11: We use the
containsKeymethod to check ifmaphas a mapping for the keyDays.MON. We gettrueas a result because the map has a mapping for the keyDays.MON. -
Line 12: We use the
containsKeymethod to check ifmaphas a mapping for the keyDays.FRI. We getfalseas a result because the map does not have mapping for the keyDays.FRI. -
Line 13: We use the
containsKeymethod to check ifmaphas a mapping for the keynull. TheEnumMapdoesn’t allownullkeys, sofalseis returned.