π Loop Through an Enum in Java β Complete Guide with Examples
π§² Introduction
Java enum
(short for enumeration) defines a fixed set of constants. You often use enums to represent days of the week, directions, states, etc.
But how do you loop through all values of an enum?
In this article, you’ll learn:
- β How to iterate over enum constants
- β Use cases of looping enums (like menus, logic flows)
- β Tips for adding fields/methods in enums
π What is an Enum in Java?
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
π Day
is an enum representing the days of the week.
π Looping Through Enum Values (Using values()
)
for (Day day : Day.values()) {
System.out.println(day);
}
β Explanation:
Day.values()
returns an array of all constants in the enum.- The enhanced
for
loop prints each value.
π‘ Best practice for looping through enums.
π‘ Example: Enum with Switch Case Logic
for (Day day : Day.values()) {
switch (day) {
case MONDAY:
System.out.println("Start of the week!");
break;
case FRIDAY:
System.out.println("Almost weekend!");
break;
case SUNDAY:
System.out.println("Rest day!");
break;
default:
System.out.println(day + " is a regular day.");
}
}
β Shows how enums integrate with control flows.
βοΈ Loop Through Enum with Fields
You can add custom fields/methods to enums:
public enum Planet {
MERCURY(3.303e+23), VENUS(4.869e+24), EARTH(5.976e+24);
private final double mass;
Planet(double mass) {
this.mass = mass;
}
public double getMass() {
return mass;
}
}
π Loop with Custom Data:
for (Planet p : Planet.values()) {
System.out.println(p + " has mass " + p.getMass());
}
β Useful in real-world simulations and config-driven systems.
π Enum Looping Comparison Table
Loop Style | Description | Use Case |
---|---|---|
for (E e : Enum.values()) | Standard enum loop | Most common usage |
Stream.of(Enum.values()) | Java 8 stream-based looping | Filtering, mapping, collecting |
EnumSet.allOf(Enum.class) | Efficient set-based enum iteration | Fast, memory-efficient enum sets |
β‘ Advanced: Using EnumSet
for Efficient Loops
import java.util.EnumSet;
EnumSet<Day> workDays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
for (Day day : workDays) {
System.out.println(day + " is a workday.");
}
β
EnumSet
is highly optimized for enum collections.
π Summary
You now know how to:
- β
Loop through enums using
.values()
- β Use enums in switch cases and with custom fields
- β
Optimize enum loops with
EnumSet
and Java Streams
Mastering enum iteration will help you build more readable, type-safe, and efficient Java applications.
βFAQ β Looping Enums in Java
βCan I get the number of enum constants?
int total = Day.values().length;
System.out.println("Total days: " + total);
β
Yes, use .length
on the result of values()
.
βCan I use streams to loop enums?
Arrays.stream(Day.values())
.filter(day -> day.toString().startsWith("S"))
.forEach(System.out::println);
β Perfect for filtering or functional-style processing (Java 8+).
βWhat if I want to associate descriptions or values with enums?
Add fields and a constructor, like:
public enum Status {
ACTIVE("A"), INACTIVE("I");
private String code;
Status(String code) { this.code = code; }
public String getCode() { return code; }
}
Loop through:
for (Status s : Status.values()) {
System.out.println(s + " = " + s.getCode());
}
Share Now :