Java Utility Library

Java EnumSet - complementOf() Method



The java.util.EnumSet.complementOf() method is used to create an enum set with the same element type as the specified enum set, initially containing all the elements of this type that are not contained in the specified set.

Syntax

public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s)

Here, E is the type of element maintained by the container.

Parameters

s Specify the enum set from whose complement to initialize this enum set.

Return Value

Returns the complement of the specified set in this set.

Exception

Throws NullPointerException, if s is null.

Example:

In the example below, the java.util.EnumSet.complementOf() method is used to create an enum set containing all the elements of specified type that are not contained in the specified set.

import java.util.*;

public class MyClass {
  
  //creating an enum
  public enum weekday{
    SUN, MON, TUE, WED, THU, FRI, SAT
  }

  public static void main(String[] args) {
    //creating EnumSets
    EnumSet<weekday> Set1;
    EnumSet<weekday> Set2;

    //add elements to Set1
    Set1 = EnumSet.of(weekday.SUN, weekday.SAT);
    
    //print the content of Set1
    System.out.println("Set1 contains: "+ Set1); 

    //populating Set2 which is complement od Set1 
    Set2 = EnumSet.complementOf(Set1);
    
    //print the content of Set2
    System.out.println("Set2 contains: "+ Set2); 
  }
}

The output of the above code will be:

Set1 contains: [SUN, SAT]
Set2 contains: [MON, TUE, WED, THU, FRI]

❮ Java.util - EnumSet