Java Remove EnumSet Elements

www.igift‮c.aedi‬om

In Java, you can remove elements from an EnumSet using the remove() method, which takes an Enum value as an argument and removes the specified element from the set. Here is an example of how to remove elements from an EnumSet:

import java.util.EnumSet;

public class EnumSetExample {

    // Define an enum type
    enum Color {
        RED, GREEN, BLUE
    }

    public static void main(String[] args) {

        // Creating an EnumSet
        EnumSet<Color> set = EnumSet.of(Color.RED, Color.GREEN, Color.BLUE);

        // Removing elements from the EnumSet
        set.remove(Color.RED);
        System.out.println("EnumSet after removing RED: " + set);

        set.removeAll(EnumSet.of(Color.GREEN, Color.BLUE));
        System.out.println("EnumSet after removing GREEN and BLUE: " + set);

        set.clear();
        System.out.println("EnumSet after clearing: " + set);
    }
}

Output:

EnumSet after removing RED: [GREEN, BLUE]
EnumSet after removing GREEN and BLUE: []
EnumSet after clearing: []

In the example above, we have created an EnumSet of the Color enum and added the RED, GREEN, and BLUE elements to it. We have then removed the RED element using the remove() method, which modifies the EnumSet in place. We have then removed the GREEN and BLUE elements using the removeAll() method, which takes another EnumSet as an argument and removes all the elements in the specified EnumSet from the original EnumSet. Finally, we have cleared the EnumSet using the clear() method, which removes all the elements from the EnumSet.

Note that you can also remove elements from an EnumSet using the retainAll() method, which retains only the elements in the specified EnumSet, and removes all other elements from the original EnumSet.