What is the EnumMap.keySet() method in Java?
EnumMap is similar to Map, except that EnumMap only takes the Enum type as key. Additionally, all the keys must be from a single enum type.
For further details on EnumMap, refer here.
In an EnumMap, we can use the keySet method to get all the keys of the EnumMap object as a Set collection.
Any changes made to the associated set are reflected in the map and vice versa. The set allows elements to be removed, and those keys that are removed from the set are also removed from the map.
Syntax
public Set<K> keySet()
Parameters
This method doesn’t take any arguments.
Return value
The keySet method will return a
Code
The example below shows how to use the keySet() method.
import java.util.EnumMap;import java.util.Set;class KeySet {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<Days> keys = map.keySet();System.out.println("The keys are -" + keys );System.out.println("\nAdding a new entry Days.WED - shoulder" );map.put(Days.WED, "shoulder");System.out.println("The keys are -" + keys );System.out.println("\nDelting the entry of the key Days.WED");map.remove(Days.WED);System.out.println("The keys are -" + keys );}}
Explanation
In the above code:
-
In line 1 and 2, we import the
EnumMapandSetclasses. -
In line 4, we have created an enum for days of the week with the name
Days. -
In line 8, we create an
EnumMapobject with the namemap. -
In line 9 and 10, we use the
putmethod to add two mappings (Days.MON="chest",Days.TUE="leg") to themapobject. -
In line 14, we get the keys of the
mapusing thekeySet()method and store them in thekeysvariable. -
In line 18, we add a new entry (
Days.WED="shoulder")to themap. -
In line 19, we print the
keys. For the newly added entry, thekey - Days.WEDis automatically available in thekeysvariable without the need to call thekeySet()method. -
In line 22, we delete the mapping for the key
Days.WEDentry of themap. The deleted entry’skeywill also be removed from thekeysvariable.