How to iteratate over Enum in Java.

March 14, 2017

To iterate over enum, you have to use values() method.
When using values() method, you can iterate through enum as if it was an array.

In this example, I use this enum.

Java 7 or lower example

1. Get element by index.

2. Iterate using enhanced loop.

In the belove example dayOfTheWeek holds the current value of enum element.

Both programs prints:

Java 8 example.

In Java 8, we can use and a lambda expression to iterate over enum.


Click here to add a comment

Leave a comment: