A 'for' loop to iterate over an enum in Java
.values()
You can call the values()
method on your enum.
for (Direction dir : Direction.values()) {
// do what you want
}
This values()
method is implicitly declared by the compiler. So it is not listed on Enum
doc.
Streams
Prior to Java 8
for (Direction dir : Direction.values()) {
System.out.println(dir);
}
Java 8
We can also make use of lambda and streams (Tutorial):
Stream.of(Direction.values()).forEachOrdered(System.out::println);
Why forEachOrdered
and not forEach
with streams ?
The behaviour of forEach
is explicitly nondeterministic where as the forEachOrdered
performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach
does not guarantee that the order would be kept.
Also when working with streams (especially parallel ones) keep in mind the nature of streams. As per the doc:
Stream pipeline results may be nondeterministic or incorrect if the behavioral parameters to the stream operations are stateful. A stateful lambda is one whose result depends on any state which might change during the execution of the stream pipeline.
Set<Integer> seen = Collections.synchronizedSet(new HashSet<>());
stream.parallel().map(e -> { if (seen.add(e)) return 0; else return e; })...
Here, if the mapping operation is performed in parallel, the results for the same input could vary from run to run, due to thread scheduling differences, whereas, with a stateless lambda expression the results would always be the same.
Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.
Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations.
All the constants of an enum type can be obtained by calling the implicit public static T[] values()
method of that type:
for (Direction d : Direction.values()) {
System.out.println(d);
}
You can do this as follows:
for (Direction direction : EnumSet.allOf(Direction.class)) {
// do stuff
}