Java Iterate Enum Using EnumSet

EnumSet is a specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient.
EnumSet provides allOf​() API to create an enum set containing all of the elements in the specified element type.

Learn more about EnumSet class with examples at EnumSet Class in Java With Examples.

Java Iterate Enum Using EnumSet

In below example, we use EnumSet provides allOf​() API to create an enum set containing all of the elements in the specified element type and iterate using forEach() API.
Here is a complete example.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Stream;

public class EnumIterationExamples {
    public static void main(String[] args) {
        System.out.println("Enum iteration using EnumSet:");
        EnumSet.allOf(DaysOfWeekEnum.class).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 EnumSet:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY


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