Search This Blog

Iterate over an Enum in Java

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

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

In this article, I would like to demonstrate 3 ways in which we can iterate over an enum in Java.

Iterate Using forEach()

Iterate Using for Loop

Iterate Using java.util.Stream

Let's first create MonthEnum class then we will see how to iterate over this enum in Java.

------------------ Using for loop -------------------
JANUARY
FEBRUARY
MARCH
APRIL
MAY
JUNE
JULY
AUGUST
SEPTEMBER
OCTOBER
NOVEMBER
DECEMBER
------------------ Using forEach() -------------------
JANUARY
FEBRUARY
MARCH
APRIL
MAY
JUNE
JULY
AUGUST
SEPTEMBER
OCTOBER
NOVEMBER
DECEMBER
------------------ Using Stream() -------------------
JANUARY
FEBRUARY
MARCH
APRIL
MAY
JUNE
JULY
AUGUST
SEPTEMBER
OCTOBER
NOVEMBER
DECEMBER