In Java, the enum type is a special Java class used to assign a predefined set of constants to a variable, such as days in a week, months in a year, etc.

In this article, you will learn about different ways to iterate over enum values in Java. Let us say we have the following enum class:

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

Iterate over enum values using the for loop

You can use the values() method to retrieve an array containing all the enum values. Once you obtain the array, you can iterate over it using the for loop, as shown below:

for (Days day : Days.values()) {
    System.out.println(day);
}

// MONDAY
// TUESDAY
// WEDNESDAY
// THURSDAY
// FRIDAY
// SATURDAY
// SUNDAY

The values() method returns an array containing the constants of the enum type, in the order, they're declared.

Iterate over enum values using forEach()

The forEach() method was introduced in Java 8 as part of the Iterable interface. So all the Java collection classes (List, Set, etc.) provides an implementation of the forEach() method.

To use the forEach() method to iterate over enum values, you first need to convert the enum into a list or a set.

Here is how you can use the Arrays.asList() method to convert an enum into a list and then use the forEach() method to iterate over all values:

Arrays.asList(Days.values()).forEach(System.out::println);

// MONDAY
// TUESDAY
// WEDNESDAY
// THURSDAY
// FRIDAY
// SATURDAY
// SUNDAY

Alternatively, you can use the EnumSet.allOf() method to convert the enum into a set and iterate over its values:

EnumSet.allOf(Days.class).forEach(System.out::println);

Iterate over enum values using Streams

The Stream class can also be used to iterate over enum values, as shown below:

Stream.of(Days.values()).forEach(System.out::println);

// MONDAY
// TUESDAY
// WEDNESDAY
// THURSDAY
// FRIDAY
// SATURDAY
// SUNDAY

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.