How to iterate the values in an enum in Java?

Java 8Object Oriented ProgrammingProgramming

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

You can iterate the contents of an enumeration using for loop, using forEach loop and, using java.util.stream.

Using for loop

You can retrieve the contents of an enum using the values() method. This method returns an array containing all the values. Once you obtain the array you can iterate it using the for loop.

Example

Following java program iterates the contents of the enum Days created above, using the for loop −

public class IterateEnum{
   public static void main(String args[]) {
      Days days[] = Days.values();
      System.out.println("Contents of the enum are: ");
      //Iterating enum using the for loop
      for(Days day: days) {
         System.out.println(day);
      }
   }
}

Output

Contents of the enum are:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Using forEach loop

You can convert the enum into a list or set and perform required actions on each element of the list using the forEach() method.

EnumSet.allOf(Days.class).forEach(day -> System.out.println(day));
Or,
Arrays.asList(Days.values()).forEach(day -> System.out.println(day));

Example

Following java program converts the enum Days created above into a set and, iterates its contents using forEach loop −

import java.util.EnumSet;
public class IterateEnum{
   public static void main(String args[]) {
      Days days[] = Days.values();
      System.out.println("Contents of the enum are: ");
      //Iterating enum using forEach loop
      EnumSet.allOf(Days.class).forEach(day -> System.out.println(day));
   }
}

Output

Contents of the enum are:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Using java.util.stream

You can use foreach loop with streams too. Therefore, using the of() method of the Stream class you can convert the contents of an enum into a stream and perform required operation on its elements using the forEach loop.

Example

Following java program converts the enum Days created above into a Stream using the of() method and, iterates its contents using forEach loop −

import java.util.stream.Stream;
public class IterateEnum{
   public static void main(String args[]) {
      Days days[] = Days.values();
      System.out.println("Contents of the enum are: ");
      //Iterating the enum using java.util.stream
      Stream.of(Days.values()).forEach(System.out::println);
   }
}

Output

Contents of the enum are:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
raja
Published on 05-Jul-2019 13:28:31
Advertisements