What is the EnumMap.remove(key,value) method in Java?
EnumMapis similar toMap, except thatEnumMaponly takes theEnumtype as keys. 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, given that the specified key-value mapping is present.
Syntax
public boolean remove(Object key, Value. v)
Parameters
The key and value whose mapping is to be removed are passed as parameters.
Return value
This method returns true if the mapping is removed.
Code
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 );}}
Explanation
In the code above, we:
-
Create an
Enumfor the subjects with the nameSubject. -
Create an
EnumMapwith the namemap. -
Add three entries to the
map. -
Use the
removemethod to remove the mapping for theSubject.MATHSkey and value50. This method checks if there is an entry present for theSubject.MATHSkey with the value50. In our case, there is an entry, so the mapping is removed and theremovemethod returnstrue. -
Use the
removemethod to remove the mapping for theSubject.SCIENCEkey and value20. This method checks if there is an entry present for theSubject.SCIENCEkey with the value20. In our case, there is no entry present, so the mapping remains unchanged and theremovemethod returnsfalse.