Explain Codes LogoExplain Codes Logo

A for-loop to iterate over an enum in Java

java
enum
best-practices
performance
Anton ShumikhinbyAnton Shumikhin·Sep 17, 2024
TLDR

Breeze through enum iteration in Java with the values() function and the for-each loop:

for (YourEnum iteration : YourEnum.values()) { System.out.println(iteration); }

The loop utilizes YourEnum's iteration and presents each on console.

Optimized Enumeration Looping

Enhancing the fast answer, you can escalate your loop's performance by caching the array resulted from values():

YourEnum[] constants = YourEnum.values(); for (YourEnum constant : constants) { System.out.println(constant); }

Java enums are organized as per their declaration. The for-each loop inherits this natural order.

Leveraging Java Streams API

Should Java 8's Stream API be within your comfort horizon, capitalize on it for elevated readability and employing advanced operations:

Arrays.stream(YourEnum.values()) .forEach(System.out::println);

The Stream API promotes predictable outcomes and thread safety by pledging statelessness and side-effect-free operations.

Embracing EnumSet

Boasting high-performance, EnumSet, designed for enums, is an adept solution for working with all enum constants:

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

EnumSet serves you with efficiency, while preserving the natural enum order, bypassing the need of an explicit index.

Diving Deeper into Advanced Iteration Techniques

Don't Mess with Indices

Sometimes you need control, for instance, to iterate in reverse order or skip elements:

YourEnum[] constants = YourEnum.values(); for (int i = constants.length-1; i >= 0; i--) { // Kicking it reverse style! System.out.println(constants[i]); }

Safety First - Thread-Safe Iterations

Concurrent contexts invite the need for safe iterations. Avoid side effects like it's the plague. Rely on atomic variables or synchronize your iteration block if that's necessary.

Enums are Not Just Constants

Enums in Java are more than just constants; they are complete classes which can have behaviors. Give life to your enums:

public enum State { START { public void process() { // Insert start logic here once done with existential crisis } }, RUN { public void process() { // Run something (not Forrest Gump) } }; // Enum acting all big brain with abstract methods public abstract void process(); } for (State state : State.values()) { state.process(); // Enums doing their thing! }