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

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

The isEmpty method of EnumMap is used to check if the specified EnumMap is empty (contains no mapping).

Syntax

public boolean isEmpty()

This method doesn’t take any argument.

This method returns true if the map doesn’t have any mappings. Otherwise, false will be returned.

Code

The following example shows how to use the isEmpty method.

import java.util.EnumMap;
class IsEmpty {
enum Days{
MON, TUE, WED, THUR, FRI, SAT, SUN
};
public static void main( String args[] ) {
EnumMap<Days, String> map = new EnumMap<>(Days.class);
System.out.println( "The map is" + map);
System.out.println("Checking if map is empty : "+ map.isEmpty());
map.put(Days.MON, "chest");
System.out.println( "\nAfter Adding an entry\nThe map is : " + map);
System.out.println("Checking if map is empty : "+ map.isEmpty());
}
}

Explanation

In the above code:

  • In line 1, we import the EnumMap class.

  • In line 3, we create an enum for days of the week with the name Days.

  • In line 7, we create an EnumMap object with the name map.

  • In line 9, we use the isEmpty method to check if the map is empty. We get true because the map has no mapping.

  • In line 11, we use the put method to add a mapping ({Days.MON="chest"}) to the map object.

  • In line 13, we use the isEmpty method to check if the map is empty. We get false because the map has one mapping in it.

Free Resources