Write a Java program to Get the complement of EnumSet collection


This Java program demonstrates the usage of the complementOf method provided by the EnumSet class to create an EnumSet object that contains all the constants of the WEEKDAY enum that are not in another EnumSet object.

The program creates an EnumSet object named enum_set that can hold the constants of the WEEKDAY enum and adds some of its constants to it. Then, it prints the contents of the enum_set. After that, the program creates an EnumSet object named com that contains all the constants of the WEEKDAY enum that are not in the enum_set using the complementOf method. Finally, it prints the contents of the com EnumSet object.

Source Code

import java.util.*;
public class Get_Complement
{
  public static void main(String[] args)
  {
    EnumSet < WEEKDAY > enum_set;
 
    //Adding elements to EnumSet.
    enum_set = EnumSet.of(WEEKDAY.Tuesday, WEEKDAY.Friday, WEEKDAY.Sunday);
    System.out.println("EnumSet : " + enum_set);
 
    EnumSet < WEEKDAY > com = EnumSet.complementOf(enum_set);
    System.out.println("Complement of EnumSet : " + com);
  }
}
enum WEEKDAY {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday 
};

Output

EnumSet : [Tuesday, Friday, Sunday]
Complement of EnumSet : [Monday, Wednesday, Thursday, Saturday]