What is the EnumMap.entrySet() 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.

In Java, the EnumMap class includes the entrySet method, which gets all the entrieskey-value mappings of the EnumMap object as a Set view.

Any changes then made to the associated set are reflected in the map as well, and vice versa. The set allows elements to be removed, and those entries that are removed from the set are also removed from the map.

Syntax

public Set<Map.Entry<K,V>> entrySet()

Parameters

This method doesn’t take any parameters.

Return value

The entrySet method returns a Set view of all the entries on the EnumMap object.

Code

The code snippet below shows how to use the entrySet method.

import java.util.EnumMap;
import java.util.Set;
import java.util.Map;
class EntrySet {
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);
Set<Map.Entry<Days, String>> entries = map.entrySet();
System.out.println("The entries are -" + entries );
System.out.println("\nAdding a new entry Days.WED - shoulder" );
map.put(Days.WED, "shoulder");
System.out.println("The entries are -" + entries );
System.out.println("\nDelting the entry of the key Days.WED");
map.remove(Days.WED);
System.out.println("The entries are -" + entries );
}
}

Explanation

In the code snippet above:

  • In lines 1 and 2, we imported the EnumMap and Set classes.

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

  • In line 8, we created an EnumMap object with the name map.

  • In lines 9 and 10, we used the put method to add two mappings {Days.MON="chest", Days.TUE="leg"} to the map object.

  • In line 14, we get the map object entries using the entrySet method, and stored them in the entries variable.

  • In line 18, we added a new entry Days.WED="shoulder" to the map.

  • In line 19, we printed the entries. The newly added entry is automatically available in the entries variable.

  • In line 22, we deleted the mapping for the key Days.WED entry of the map. The deleted entry will also be removed from the entries variable.

Free Resources