Iterating over Enum Values in Java

JavaObject Oriented ProgrammingProgramming

The Enum class is the common base class of all Java language enumeration types.

Example

Let us see an example to iterate over enum values using for loop −

public class Demo {
   public enum Vehicle { CAR, BUS, BIKE }
   public static void main(String[] args) {
      for (Vehicle v : Vehicle.values())
         System.out.println(v);
   }
}

Output

CAR
BUS
BIKE

Example

Let us now see another example to iterate over enum values using for each −

import java.util.stream.Stream;
public class Demo {
   public enum Work { TABLE, CHAIR, NOTEPAD, PEN, LAPTOP }
   public static void main(String[] args) {
      Stream.of(Work.values()).forEach(System.out::println);
   }
}

Output

TABLE
CHAIR
NOTEPAD
PEN
LAPTOP
raja
Published on 25-Sep-2019 08:59:31
Advertisements