What is the EnumMap.size() 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 size() method of EnumMap will return the number of key-value mappings present in this map.

Syntax


public int size()

Argument

This method doesn’t take any argument.

Return value

This method returns an integer value denoting the number of mappings present in the map.

Code

The example below shows how to use the size() method:

import java.util.EnumMap;
class Size {
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");
map.put(Days.TUE, "leg");
System.out.println( "The map is : " + map);
System.out.println( "The size is : " + map.size());
}
}

Explanation

In the above code:

  • In line 1, we import the EnumMap class.

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

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

  • In lines 8-9, we use the put() method to add two mappings {Days.MON="chest",Days.TUE="leg"}to the map object.

  • In line 11, we use the size method to get the number of key-value mappings present in. the map. We get 2 as result.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources