Java program to check an EnumSet collection contains a specified item

Given an EnumSet collection, and an item, we have to check whether EnumSet contains the item or not.
Submitted by Nidhi, on May 29, 2022

Problem Solution:

In this program, we will create an Enum for COLORS constants. Then we will create an EnumSet collection and add elements to it. After that, we will check whether an EnumSet collection contains a specified item or not using contains() method.

Program/Source Code:

The source code to check an EnumSet collection contains a specified item is given below. The given program is compiled and executed successfully.

// Java program to check an EnumSet collection 
// contains a specified item

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 = EnumSet.noneOf(COLORS.class);

    enumSet.add(COLORS.RED);
    enumSet.add(COLORS.GREEN);
    enumSet.add(COLORS.BLUE);

    if (enumSet.contains(COLORS.GREEN))
      System.out.println("The enumSet contains COLORS.GREEN constant.");
    else
      System.out.println("The enumSet does not contain COLORS.GREEN constant.");

    if (enumSet.contains(COLORS.WHITE))
      System.out.println("The enumSet contains COLORS.WHITE constant.");
    else
      System.out.println("The enumSet does not contain COLORS.WHITE constant.");
  }
}

Output:

The enumSet contains COLORS.GREEN constant.
The enumSet does not contain COLORS.WHITE constant.

Explanation:

Here, we created an EnumSet collection and add elements to it. Then we used contains() method to check a specified item is contained in the enumSet collection.

Java EnumSet Programs »






Comments and Discussions!

Load comments ↻






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