What is the EnumMap.remove(key) method in Java?
EnumMapis similar toMap, except thatEnumMaponly takes theEnumtype as a key. Also, all the keys must be from a singleEnumtype. For further details, refer here.
In EnumMap, we can use the remove method to remove the mapping of the specified key.
Syntax
public V remove(Object key)
Parameters
The key whose mapping is to be removed is passed as an argument.
Return value
-
If there is a mapping present for the specified key, then the mapping is removed and the removed value is returned.
-
If there is no mapping present for the specified key, then
nullis returned.
Code
The code snippet below shows how to use the remove method.
import java.util.EnumMap;class Remove {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");String returnValue = map.remove(Days.MON);System.out.println("\nThe return value for map.remove(Days.MON) - " + returnValue);System.out.println("The map is -" + map );returnValue = map.remove(Days.WED);System.out.println("\nThe return value for map.remove(Days.WED) - " + returnValue);System.out.println("The map is -" + map );}}
Explanation
In the code snippet 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 and 9, we use the
putmethod to add two mappings{Days.MON="chest", Days.TUE="leg"}to themapobject. -
In line 11, we use the
removemethod to remove the mapping for the keyDays.MON. There is a mapping for the keyDays.MON, so it will be removed and the valuechestmapped to that will be returned. -
In line 14, we use the
removemethod to remove the mapping for the keyDays.WED. There is no such entry present, sonullwill be returned.