Home >Java >javaTutorial >Iterate over enum values ​​in Java

Iterate over enum values ​​in Java

WBOY
WBOYforward
2023-09-12 11:01:02907browse

Iterate over enum values ​​in Java

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

Now let’s look at another example, using for each loop to iterate over enumeration values:

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

The above is the detailed content of Iterate over enum values ​​in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete