EnumMap
is similar toMap
, except thatEnumMap
only takes theEnum
type as keys. Also, all the keys must be from a singleenum
type. For further details, refer here.
In EnumMap
, we can use the remove
method to remove the mapping, given that the specified key-value mapping is present.
public boolean remove(Object key, Value. v)
The key
and value
whose mapping is to be removed are passed as parameters.
This method returns true
if the mapping is removed.
The following example shows how to use the remove
method.
import java.util.EnumMap;class Remove {enum Subject {MATHS, SCIENCE, PROGRAMMING, ECONOMICS};public static void main( String args[] ) {EnumMap<Subject, Integer> map = new EnumMap<>(Subject.class);map.put(Subject.MATHS, 50);map.put(Subject.SCIENCE, 60);map.put(Subject.PROGRAMMING, 70);System.out.println("The map is -" + map );System.out.println("\nCalling remove(MATHS, 50)" );boolean isRemoved = map.remove(Subject.MATHS, 50);System.out.println("Is mapping removed -" + isRemoved);System.out.println("The map is -" + map );System.out.println("\nCalling remove(SCIENCE, 60)" );isRemoved = map.remove(Subject.SCIENCE, 20);System.out.println("Is mapping removed -" + isRemoved);System.out.println("The map is -" + map );}}
In the code above, we:
Create an Enum
for the subjects with the name Subject
.
Create an EnumMap
with the name map
.
Add three entries to the map
.
Use the remove
method to remove the mapping for the Subject.MATHS
key and value 50
. This method checks if there is an entry present for the Subject.MATHS
key with the value 50
. In our case, there is an entry, so the mapping is removed and the remove
method returns true
.
Use the remove
method to remove the mapping for the Subject.SCIENCE
key and value 20
. This method checks if there is an entry present for the Subject.SCIENCE
key with the value 20
. In our case, there is no entry present, so the mapping remains unchanged and the remove
method returns false
.