Java Utility Library

Java EnumMap - containsKey() Method



The java.util.EnumMap.containsKey() method returns true if this map contains a mapping for the specified key.

Syntax

public boolean containsKey(Object key)

Parameters

key Specify the key whose presence in this map is to be tested.

Return Value

Returns true if this map contains a mapping for the specified key.

Exception

NA.

Example:

In the example below, the java.util.EnumMap.containsKey() method is used to check the presence of specified key in the given EnumMap.

import java.util.*;

public class MyClass {
  
  //creating an enum
  public enum weekday{
    SUN, MON, TUE, WED, THU, FRI, SAT
  }

  public static void main(String[] args) {
    //creating an EnumMap
    EnumMap<weekday,Integer> MyMap = 
        new EnumMap<weekday,Integer>(weekday.class);

    //associate values in the map
    MyMap.put(weekday.MON, 1);
    MyMap.put(weekday.TUE, 2);
    MyMap.put(weekday.WED, 3);
    MyMap.put(weekday.THU, 4);
    MyMap.put(weekday.FRI, 5);

    //printing EnumMap
    System.out.println("MyMap contains: " + MyMap);   

    //check the presence of SUN key
    System.out.print("Does MyMap contain SUN key? - ");  
    System.out.println(MyMap.containsKey(weekday.SUN));  

    //check the presence of FRI key
    System.out.print("Does MyMap contain FRI key? - ");  
    System.out.println(MyMap.containsKey(weekday.FRI));  
  }
}

The output of the above code will be:

MyMap contains: {MON=1, TUE=2, WED=3, THU=4, FRI=5}
Does MyMap contain SUN key? - false
Does MyMap contain FRI key? - true

❮ Java.util - EnumMap