Java program to get the complement of EnumSet collection

Given an EnumSet collection, we have to get the complement of it.
Submitted by Nidhi, on May 27, 2022

Problem Solution:

In this program, we will create an Enum for COLORS constants. Then we will create an EnumSet and get its complement using the complementOf() method.

Program/Source Code:

The source code to get the complement of the EnumSet collection is given below. The given program is compiled and executed successfully.

// Java program to get the complement of 
// EnumSet collection

import java.util.*;

//Enum for color constants
enum COLORS {
  RED,
  GREEN,
  BLUE,
  BLACK,
  WHITE
};

public class Main {
  public static void main(String[] args) {
    EnumSet < COLORS > enumSet;

    //Adding elements to EnumSet.
    enumSet = EnumSet.of(COLORS.BLUE, COLORS.BLACK, COLORS.GREEN);

    System.out.println("EnumSet is: " + enumSet);

    EnumSet < COLORS > complement = EnumSet.complementOf(enumSet);
    System.out.println("Complement of enumSet is: " + complement);
  }
}

Output:

EnumSet is: [GREEN, BLUE, BLACK]
Complement of enumSet is: [RED, WHITE]

Explanation:

The Main class contains a main() method. The main() method is the entry point for the program. And, created a reference of the EnumSet collection and initialized it with elements of COLORS elements using Of() method. After that, we get the complement of enumSet using the complementOf() method and printed the result.

Java EnumSet Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.