Write a Java program to traverse and print EnumSet collection using foreach loop


This Java code demonstrates the usage of EnumSet and foreach loop. Here's a brief explanation of the code:

  • The program defines an enum type WEEKDAY with seven values representing days of the week.
  • The main method begins by creating an empty EnumSet object using the noneOf method, which takes the type of enum as an argument.
  • The program adds three WEEKDAY values to the EnumSet using the add method.
  • Finally, the program uses a foreach loop to print the values of the EnumSet on the console. The loop iterates over each element of the EnumSet and prints it on the console.

Source Code

import java.util.*;
public class Foreach_Loop
{
	public static void main(String[] args)
	{
		EnumSet < WEEKDAY > item = EnumSet.noneOf(WEEKDAY.class);
 
		item.add(WEEKDAY.Wednesday);
		item.add(WEEKDAY.Friday);
		item.add(WEEKDAY.Tuesday);
 
		System.out.print("Elements of EnumSet : ");
		for (WEEKDAY i: item)
		{
			System.out.print(i+" ");
		}
	}
}
enum WEEKDAY {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday 
};

Output

Elements of EnumSet : Tuesday Wednesday Friday