Java Program to Iterate over enum



In this article, we will understand how to iterate over enum objects. Enum is a datatype that represents a small collection of objects.

Below is a demonstration of the same −

Input

Suppose our input is −

Enum objects are defined as : red, blue, green, yellow, orange

Output

The desired output would be −

Printing the Objects: red
blue
green
yellow
orange

Algorithm

Step 1 – START
Step 2 - Declare the objects of Enum function namely red, blue, green, yellow, orange
Step 3 – Using a for loop, iterate over the objects of the enum function and print each object.
Step 4- Stop

Example 1

enum Enum {
   red, blue, green, yellow, orange;
}
public class Colour {
   public static void main(String[] args) {
      System.out.println("The values of Enum function are previously defined .");
      System.out.println("Accessing each enum constants");
      for(Enum colours : Enum.values()) {
         System.out.print(colours + "\n");
      }
   }
}

Output

The values of Enum function are previously defined .
Accessing each enum constants
red
blue
green
yellow
orange

Example 2

Here is an example to print the days of the week.

import java.util.EnumSet;
enum Days {
   Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
public class IterateEnum{
   public static void main(String args[]) {
      Days my_days[] = Days.values();
      System.out.println("Values of the enum are: ");
      EnumSet.allOf(Days.class).forEach(day -> System.out.println(day));
   }
}

Output

Values of the enum are:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Advertisements