What is the EnumMap.remove(key) method in Java?

EnumMap is similar to Map, except that EnumMap only takes the Enum type as a key. Also, all the keys must be from a single Enum type. 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 null is 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 EnumMap class.

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

  • In line 7, we create an EnumMap object with the name map.

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

  • In line 11, we use the remove method to remove the mapping for the key Days.MON. There is a mapping for the key Days.MON, so it will be removed and the value chest mapped to that will be returned.

  • In line 14, we use the remove method to remove the mapping for the key Days.WED. There is no such entry present, so null will be returned.

Free Resources