Java Iterate Enum Using forEach

The forEach() method was added to the Iterable interface in Java 8. So all the java collection classes have implementations of a forEach() method. In order to use these with an Enum, we first need to convert the Enum to a suitable collection. We can use Arrays.asList() to generate an ArrayList which we can then loop around using the forEach() method.

Java Iterate Enum Using forEach

import java.util.Arrays;

public class EnumIterationExample {
    public static void main(String[] args) {
        System.out.println("Enum iteration using Arrays.asList():");
        Arrays.asList(DaysOfWeekEnum.values()).forEach(day - > System.out.println(day));
    }
}


enum DaysOfWeekEnum {
    SUNDAY("off"),
        MONDAY("working"),
        TUESDAY("working"),
        WEDNESDAY("working"),
        THURSDAY("working"),
        FRIDAY("working"),
        SATURDAY("off");

    private String typeOfDay;

    DaysOfWeekEnum(String typeOfDay) {
        this.typeOfDay = typeOfDay;
    }

    public String getTypeOfDay() {
        return typeOfDay;
    }

    public void setTypeOfDay(String typeOfDay) {
        this.typeOfDay = typeOfDay;
    }
}
Output:
Enum iteration using Arrays.asList():
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Comments