What is the EnumMap.entrySet() method in Java?
EnumMapis similar toMap, except thatEnumMaponly takes theEnumtype as key. Also, all the keys must be from a singleEnumtype. For further details, refer here.
In Java, the EnumMap class includes the entrySet method, which gets all 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
EnumMapandSetclasses. -
In line 4, we created an
enumfor days of the week with the nameDays. -
In line 8, we created an
EnumMapobject with the namemap. -
In lines 9 and 10, we used the
putmethod to add two mappings{Days.MON="chest", Days.TUE="leg"}to themapobject. -
In line 14, we get the
mapobject entries using theentrySetmethod, and stored them in theentriesvariable. -
In line 18, we added a new entry
Days.WED="shoulder"to themap. -
In line 19, we printed the
entries. The newly added entry is automatically available in theentriesvariable. -
In line 22, we deleted the mapping for the key
Days.WEDentry of themap. The deleted entry will also be removed from theentriesvariable.