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.

Example 1: Java Iterate Enum Using EnumSet using forEach Method

In the below example, we use EnumSet provided allOf​() API to create an enum set containing all of the elements in the specified element type and iterate using forEach() API.
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

Example 2: Java Iterate Enum Using EnumSet using for each Loop

import java.util.EnumSet;

public class EnumIterationExample {

    // Define an `enum` for days of the week
    enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    }

    public static void main(String[] args) {
        // 1. Create an `EnumSet` with all days
        EnumSet<Day> allDays = EnumSet.allOf(Day.class);

        // 2. Iterate through the days using a for-each loop
        System.out.println("Iterating through all days:");
        for (Day day : allDays) {
            System.out.println(day);
        }
    }
}

Output:

Iterating through all days:
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

Explanation:

1. Using EnumSet.allOf(), we can create an EnumSet that includes all the values of the Day enum.

2. A for-each loop is then utilized to iterate over each day present in the EnumSet.

The EnumSet provides an efficient and type-safe way to perform operations on sets of enumerated types.

Comments