Write a Java program to Remove Elements of an EnumSet collection that does not exist in another EnumSet collection


This Java program demonstrates the use of EnumSet class to perform set operations like adding, removing and retaining elements from an EnumSet. Explanation of the program:

  • We start by importing the java.util package which contains the EnumSet class and other necessary classes and interfaces.
  • Next, we define a class named "Remove_Element".
  • Inside the class, we define the main method which is the entry point of our program.
  • We create two EnumSet objects named enum_set1 and enum_set2 by calling the static method "noneOf" of the EnumSet class. This method returns an empty EnumSet with the specified element type.
  • We add some elements to both the enum sets using the "add" method. Here, we add Monday, Tuesday, Wednesday and Saturday to enum_set1 and Monday and Saturday to enum_set2.
  • We then print the elements of both the enum sets using the "println" method of System.out object.
  • We perform set intersection on enum_set1 and enum_set2 using the "retainAll" method of EnumSet class. This method retains only the elements that are present in both the sets. The resulting enum_set1 contains only Monday and Saturday, as these are the only elements common to both the sets.
  • Finally, we print the resulting enum sets after performing set intersection.

Source Code

import java.util.*;
public class Remove_Element
{
	public static void main(String[] args)
	{
		EnumSet < WEEKDAY > enum_set1 = EnumSet.noneOf(WEEKDAY.class);
		EnumSet < WEEKDAY > enum_set2 = EnumSet.noneOf(WEEKDAY.class);
 
		enum_set1.add(WEEKDAY.Monday);
		enum_set1.add(WEEKDAY.Tuesday);
		enum_set1.add(WEEKDAY.Wednesday);
		enum_set1.add(WEEKDAY.Saturday);
 
		enum_set2.add(WEEKDAY.Monday);
		enum_set2.add(WEEKDAY.Saturday);
 
		System.out.println("Elements of EnumSet 1 : " + enum_set1);
		System.out.println("Elements of EnumSet 2 : " + enum_set2);
 
		enum_set1.retainAll(enum_set2);
 
		System.out.println("\nElements of EnumSet 1 : " + enum_set1);
		System.out.println("Elements of EnumSet 2 : " + enum_set2);
	}
}
enum WEEKDAY {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday 
};

Output

Elements of EnumSet 1 : [Monday, Tuesday, Wednesday, Saturday]
Elements of EnumSet 2 : [Monday, Saturday]

Elements of EnumSet 1 : [Monday, Saturday]
Elements of EnumSet 2 : [Monday, Saturday]