I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

Enum in Java is a datatype that helps us assign a predefined set of constants to a variable.

In this quick article, we’ll see different ways in which we can iterate over an enum in Java.

2. Iterating over Enum Values

Let’s first define an enum class, which we’ll use in our examples:

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

Enums do not have methods for iteration like forEach() or iterator(). Instead, it has a method called values() which returns the predefined values.

2.1. Iterate Using forEach()

In order to perform the iteration using forEach(), we need to convert the enum into a list or a set.

First, we use EnumSet, which is a specialized set implementation to use with Enum types:

EnumSet.allOf(DaysOfWeekEnum.class)
  .forEach(day -> System.out.println(day));

Similarly, we can use Arrays:

Arrays.asList(DaysOfWeekEnum.class)
  .forEach(day -> System.out.println(day));

Here, EnumSet and Arrays convert the enum into Set and List respectively.

2.2. Iterate Using Stream

We can also use java.util.stream if we want to perform any parallel aggregate operations.

Again, to create Stream we have two options, one using Stream.of:

Stream.of(DaysOfWeekEnum.values());

Another, using Arrays:

Arrays.stream(DaysOfWeekEnum.values());

Here, values() is an Enum method, which returns all the predefined values.

Now, let us extend the DaysOfWeekEnum class to create an example using Stream:

public 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;
    }
}

Now we will write an example to return the non-working days:

public class EnumStreamExample {

    public static void main() {
        DaysOfWeekEnum.stream()
        .filter(d -> d.getTypeOfDay().equals("off"))
        .forEach(System.out::println);
    }

    public static Stream<DaysOfWeekEnum> stream() {
        return Stream.valueOf(DaysOfWeekEnum.values()); 
    }
}

The output we get when we run this:

SUNDAY
SATURDAY

2.3. Iterate Using for loop

Lastly, we can simply use the old-school for loop:

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

3. Conclusion

We saw various ways to iterate over an enum using forEach, Stream, and for loop in Java. If we need to perform any parallel operations, Stream would be a good option.

Otherwise, there is no restriction on which method to use.

As always, the code for all the examples explained here can be found over on GitHub.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS