Java Remove EnumMap Elements
To remove elements from an EnumMap
in Java, you can use the remove()
method. Here's an example that demonstrates how to remove a key-value pair from an EnumMap
:
import java.util.EnumMap; enum Color { RED, GREEN, BLUE; } public class Example { public static void main(String[] args) { EnumMap<Color, Integer> colorMap = new EnumMap<>(Color.class); colorMap.put(Color.RED, 1); colorMap.put(Color.GREEN, 2); colorMap.put(Color.BLUE, 3); System.out.println(colorMap); colorMap.remove(Color.GREEN); System.out.println(colorMap); } }
In this example, we first define an enum
called Color
, which has three values: RED
, GREEN
, and BLUE
. We then create a new EnumMap
object that maps Color
keys to Integer
values. We use the put()
method to insert key-value pairs into the EnumMap
.
To remove an element from the EnumMap
, we call the remove()
method, passing in the key for the element we want to remove. In this case, we remove the element associated with the GREEN
key.
After removing the element, we print out the contents of the EnumMap
using the toString()
method again. This will output the following:
{RED=1, GREEN=2, BLUE=3} {RED=1, BLUE=3}
As you can see, the GREEN
key-value pair has been removed from the EnumMap
.