Java Utility Library

Java EnumMap - remove() Method



The java.util.EnumMap.remove() method is used to remove the mapping for the specified key from this map if present.

Syntax

public V remove(Object key)

Here, V is the type of value maintained by the container.


Parameters

key Specify key whose mapping is to be removed from the map.

Return Value

Returns the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

Exception

NA.

Example:

In the example below, the java.util.EnumMap.remove() method is used to remove the mapping for the specified key from the given map.

import java.util.*;

public class MyClass {
  
  //creating an enum
  public enum weekday{
    MON, TUE, WED, THU, FRI
  }

  public static void main(String[] args) {
    //creating EnumMap
    EnumMap<weekday,Integer> MyMap = 
        new EnumMap<weekday,Integer>(weekday.class);

    //associate values in MyMap
    MyMap.put(weekday.MON, 1);
    MyMap.put(weekday.TUE, 2);
    MyMap.put(weekday.WED, 3);
    MyMap.put(weekday.THU, 4);
    MyMap.put(weekday.FRI, 5);

    //printing MyMap
    System.out.println("Before remove, MyMap contains: " + MyMap);    

    //remove mapping for "MON" key
    MyMap.remove(weekday.MON); 

    //printing MyMap
    System.out.println("After remove, MyMap contains: " + MyMap);  
  }
}

The output of the above code will be:

Before remove, MyMap contains: {MON=1, TUE=2, WED=3, THU=4, FRI=5}
After remove, MyMap contains: {TUE=2, WED=3, THU=4, FRI=5}

❮ Java.util - EnumMap