首页 > 文章列表 > 在Java中迭代枚举值

在Java中迭代枚举值

Java迭代器枚举值
405 2023-08-29

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

输出

CAR
BUS
BIKE

Example

现在让我们看另一个例子,使用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);
   }
}

输出

TABLE
CHAIR
NOTEPAD
PEN
LAPTOP