Example 1: Loop through enum using forEach loop
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
class Main {
public static void main(String[] args) {
System.out.println("Access each enum constants");
// use foreach loop to access each value of enum
for(Size size : Size.values()) {
System.out.print(size + ", ");
}
}
}
Output 1
Access each enum constants SMALL, MEDIUM, LARGE, EXTRALARGE,
In the above example, we have an enum named Size. Notice the expression,
Size.values()
Here, the values()
method converts the enum constants in an array of the Size type. We then used the forEach loop to access each element of the enum.
Example 2: Loop through enum using EnumSet Class
import java.util.EnumSet;
// create an enum
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
class Main {
public static void main(String[] args) {
// create an EnumSet class
// convert the enum Size into the enumset
EnumSet<Size> enumSet = EnumSet.allOf(Size.class);
System.out.println("Elements of EnumSet: ");
// loop through the EnumSet class
for (Size constant : enumSet) {
System.out.print(constant + ", ");
}
}
}
Output
Elements of EnumSet: SMALL, MEDIUM, LARGE, EXTRALARGE,
Here, we have used the allOf()
method to create an EnumSet
class from the enum Size. We then access each element of the enumset class using the forEach
loop.