How to iterate over enum values in Java

In Java, the enum type is a special Java class used to assign a predefined set of constants to a variable, such as days in a week, months in a year, etc.

In this article, you will learn about different ways to iterate over enum values in Java. Let us say we have the following enum class:

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

Iterate over enum values using the for loop

You can use the values() method to retrieve an array containing all the enum values. Once you obtain the array, you can iterate over it using the for loop, as shown below:

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

// MONDAY
// TUESDAY
// WEDNESDAY
// THURSDAY
// FRIDAY
// SATURDAY
// SUNDAY

The values() method returns an array containing the constants of the enum type, in the order, they're declared.

Iterate over enum values using forEach()

The forEach() method was introduced in Java 8 as part of the Iterable interface. So all the Java collection classes (List, Set, etc.) provides an implementation of the forEach() method.

To use the forEach() method to iterate over enum values, you first need to convert the enum into a list or a set.

Here is how you can use the Arrays.asList() method to convert an enum into a list and then use the forEach() method to iterate over all values:

Arrays.asList(Days.values()).forEach(System.out::println);

// MONDAY
// TUESDAY
// WEDNESDAY
// THURSDAY
// FRIDAY
// SATURDAY
// SUNDAY

Alternatively, you can use the EnumSet.allOf() method to convert the enum into a set and iterate over its values:

EnumSet.allOf(Days.class).forEach(System.out::println);

Iterate over enum values using Streams

The Stream class can also be used to iterate over enum values, as shown below:

Stream.of(Days.values()).forEach(System.out::println);

// MONDAY
// TUESDAY
// WEDNESDAY
// THURSDAY
// FRIDAY
// SATURDAY
// SUNDAY

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.