What is the EnumMap.get() method in Java?
The get method can be used to get the value associated with the specified key in the EnumMap. If the key has no mapping, then null is returned.
EnumMapis similar toMap, except thatEnumMaponly takes theEnumtype as key. Also, all the keys must be from a singleenumtype. For further details, refer here.
Syntax
The following is the syntax for the get method of EnumMap:
public V get(Object key)
Parameters
The method expects the key for the value to be returned as an argument.
Return Value
The get method of EnumMap will return:
-
The
Valueassociated with the passedkeyif there is a mapping present for the passedkey. -
nullif there is no mapping present for the passedkey.
Code
The code below demonstrates how to use the get method:
import java.util.EnumMap;class Gett {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");System.out.println( "The map is" + map);System.out.println("map.get(Days.MON) : "+ map.get(Days.MON));System.out.println("map.get(Days.FRI) : "+ map.get(Days.FRI));}}
Explanation
In the code above:
-
In line 1, we import the
EnumMapclass. -
In line 3, we create an
enumfor days of the week with the nameDays. -
In line 7, we create an
EnumMapobject with the namemap. -
In line 8, we use the
putmethod to add a mappingDays.MON="chest"to themapobject. -
In line 10, we call the
getmethod for the keyDays.MON. This will return the value associated with the keyDays.MON. In our case,"chest"is returned. -
In line 11, we call the
getmethod for the keyDays.FRI. This will returnnullbecause there is no value associated with the keyDays.FRI.