A for-loop to iterate over an enum in Java

Viewed 502265

I have an enum in Java for the cardinal and 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?

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

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
}

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

Scenario: Let's say, we have a fixed number of card types. Each card type has fees and a joining bonus associated with it.

package enumPkg;

public enum CardTypes {
//Each enum is object
DEBIT(10,20),
CREDIT(0,10),
CRYPTO(5,30);

//Object properties
int fees;
int bonus;

//Initilize object using constructor
CardTypes(int fee, int bonus){
    this.fees = fee;
    this.bonus = bonus;
}

//access object property
public int getFees(){
    return this.fees;
}

public int getBonus(){
    return this.bonus;
}

}

Now to access enum in other class. Follow the below process in java:

package enumPkg;

public class EnumClass {
public static void main(String[] args) {
    CardTypes cardType = CardTypes.CREDIT; //Each enum element is public static final, when accessed returns a object
    System.out.println(cardType);

    System.out.println("Debit card fees : "+CardTypes.DEBIT.getFees());
    System.out.println("Debit card bonus : "+CardTypes.DEBIT.getBonus());

    CardTypes[] cardTypes = CardTypes.values();//return array of CardTypes i.e all enum elements we have defined

    for (CardTypes type : CardTypes.values()) {
        System.out.println(type); //particular enum object
        System.out.println(type.ordinal()); //return enum position
        System.out.println("Bonus : "+type.getBonus()); //return enum object property: Bonus
        System.out.println("Fees  : "+type.getFees());//return enum object property: Fees
    }

}
}

Output:

CREDIT
Debit card fees : 10
Debit card bonus : 20
DEBIT
0
Bonus : 20
Fees  : 10
CREDIT
1
Bonus : 10
Fees  : 0
CRYPTO
2
Bonus : 30
Fees  : 5
Related