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.
Learn and master Java Collections Framework at Learn Java Collections Framework

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

Related Collections Examples

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments