×

Java Programs

Java Practice

Java program to traverse and print EnumSet collection using 'foreach' loop

Given an EnumSet collection, we have to traverse and print it using 'foreach' loop.
Submitted by Nidhi, on May 29, 2022

Problem statement

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 traverse and print created EnumSet collection using the "foreach" loop.

Source Code

The source code to traverse and print the EnumSet collection using the "foreach" loop is given below. The given program is compiled and executed successfully.

// Java program to traverse and print EnumSet collection 
// using "foreach" loop

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);

    System.out.println("Elements of enumSet: ");
    for (COLORS item: enumSet)
      System.out.println(" " + item);
  }
}

Output

Elements of enumSet: 
 RED
 GREEN
 BLUE

Explanation

The Main class contains a main() method. The main() method is the entry point for the program. And, created an EnumSet collection and add elements to it. Then we traversed and printed elements of created EnumSet using the "foreach" loop.

Java EnumSet Programs »





Comments and Discussions!

Load comments ↻





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