[java] A 'for' loop to iterate over an enum in Java

I have an enum in Java for the cardinal & intermediate directions:

public enum Direction {
   NORTH,
   NORTHEAST,
   EAST,
   SOUTHEAST,
   SOUTH,
   SOUTHWEST,
   WEST,
   NORTHWEST
}

How can I write a for loop that iterates through each of these enum values?

This question is related to java loops for-loop enums

The answer is


.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.


    for (Direction  d : Direction.values()) {
       //your code here   
    }

Try to use a for each

for ( Direction direction : Direction.values()){
  System.out.println(direction.toString());
}

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.


for(Direction dir : Direction.values())
{

}

Java8

Stream.of(Direction.values()).forEach(System.out::println);

from Java5+

for ( Direction d: Direction.values()){
 System.out.println(d);
}

values() method may simply work:

for (Direction  d : Direction.values()) {
   //whatever you want to do with each of these enum values  
}

You can do this as follows:

for (Direction direction : EnumSet.allOf(Direction.class)) {
  // do stuff
}

If you don't care about the order this should work:

Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
    // do stuff
}

More methods in java 8:

Using EnumSet with forEach

EnumSet.allOf(Direction.class).forEach(...);

Using Arrays.asList with forEach

Arrays.asList(Direction.values()).forEach(...);

we can use a filter(JAVA 8) like this.

Stream.of(Direction.values()).filter(name -> !name.toString().startsWith("S")).forEach(System.out::println);

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);
 }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to enums

Enums in Javascript with ES6 Check if value exists in enum in TypeScript Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'? TypeScript enum to object array How can I loop through enum values for display in radio buttons? How to get all values from python enum class? Get enum values as List of String in Java 8 enum to string in modern C++11 / C++14 / C++17 and future C++20 Implementing Singleton with an Enum (in Java) Swift: Convert enum value to String?