Iterating over Enum Values in Java

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, so that we can create some simple code examples:

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

Enums do not have methods for iteration like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

2.1. Iterate Using for Loop

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

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

2.2. Iterate Using Stream

We can also use java.util.Stream. So that we can perform operations on the Enum values.

To create a Stream we have two options, one using Stream.of:

Stream.of(DaysOfWeekEnum.values());

Another, using Arrays.stream:

Arrays.stream(DaysOfWeekEnum.values());

So, 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;
    }
	
    // standard getters and setters 

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

Now we will write an example in order to print the non-working days:

public class EnumStreamExample {

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

The output we get when we run this:

SUNDAY
SATURDAY

2.3. Iterate 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:

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

2.4. Iterate Using EnumSet

EnumSet is a specialized set implementation that we can use with Enum types:

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

2.5. Using an ArrayList of Enum Values

We can also add values of an Enum to a List. This allows us to manipulate the List like any other:

List<DaysOfWeekEnum> days = new ArrayList<>();
days.add(DaysOfWeekEnum.FRIDAY);
days.add(DaysOfWeekEnum.SATURDAY);
days.add(DaysOfWeekEnum.SUNDAY);
for (DaysOfWeekEnum day : days) {
    System.out.println(day);
}
days.remove(DaysOfWeekEnum.SATURDAY);
if (!days.contains(DaysOfWeekEnum.SATURDAY)) {
    System.out.println("Saturday is no longer in the list");
}
for (DaysOfWeekEnum day : days) {
    System.out.println(day);
}

We can also create an ArrayList by using Arrays.asList().

However, as the ArrayList is backed by the Enum values array it will be immutable, so we can’t add or remove items from the List. The remove in the following code would fail with an UnsupportedOperationException:

List<DaysOfWeekEnum> days = Arrays.asList(DaysOfWeekEnum.values());
days.remove(0);

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.

Related posts:

Redirect to Different Pages after Login with Spring Security
Custom Error Pages with Spring MVC
Hướng dẫn sử dụng luồng vào ra ký tự trong Java
Java Program to Implement Stein GCD Algorithm
Java Program to Implement Multi-Threaded Version of Binary Search Tree
An Intro to Spring Cloud Contract
Java Program to Implement PrinterStateReasons API
Spring – Injecting Collections
Hướng dẫn Java Design Pattern – State
Java Program to Implement Johnson’s Algorithm
Interface trong Java 8 – Default method và Static method
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Write/Read cookies using HTTP and Read a file from the internet
Initialize a HashMap in Java
Comparing Two HashMaps in Java
Java Program to Implement Patricia Trie
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Một số nguyên tắc, định luật trong lập trình
Java Program to Find All Pairs Shortest Path
Convert XML to JSON Using Jackson
Collect a Java Stream to an Immutable Collection
Xử lý ngoại lệ trong Java (Exception Handling)
Guide to the Java Queue Interface
Rate Limiting in Spring Cloud Netflix Zuul
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Guide to the Synchronized Keyword in Java
Tránh lỗi NullPointerException trong Java như thế nào?
New Features in Java 12
Java Program to Perform Searching Using Self-Organizing Lists
Java Program to Implement Direct Addressing Tables
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
How to Read a Large File Efficiently with Java