Home » Java » A 'for' loop to iterate over an enum in Java

A 'for' loop to iterate over an enum in Java

Posted by: admin November 2, 2017 Leave a comment

Questions:

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?

Answers:

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

Questions:
Answers:

Enum#values():

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

Questions:
Answers:

You can do this as follows:

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

Questions:
Answers:

Streams

Prior to Java 8 we need to print the values using for loop, like:

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

But in Java 8 we can also make use of lambda and streams (Tutorial):

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

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

}

Questions:
Answers:

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

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

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

Questions:
Answers:

Java8

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

from Java5+

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

Questions:
Answers:

Try to use a for each

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

Questions:
Answers:

This is how to iterate over Enum:

private static void iterateEnumValues() {
        System.out.println("Iterating over Direction enum");
        for(Direction direction : Direction.values())
        {
            System.out.println("Enum = " + direction);
        }
}

To know more about common Enum operations, check this: How to use Enums in java