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
登录后复制
以上就是在Java中迭代枚举值的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!