在 Java 中迭代枚举的“for”循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1104975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:49:08  来源:igfitidea点击:

A 'for' loop to iterate over an enum in Java

javaloopsfor-loopenums

提问by Nick Meyer

I have an enumin Java for the cardinal & intermediate directions:

我有一个enum在 Java 中的主要和中间方向:

public enum Direction {
   NORTH,
   NORTHEAST,
   EAST,
   SOUTHEAST,
   SOUTH,
   SOUTHWEST,
   WEST,
   NORTHWEST
}

How can I write a forloop that iterates through each of these enumvalues?

如何编写一个for循环遍历这些enum值中的每一个?

采纳答案by notnoop

.values()

.values()

You can call the values()method on your enum.

您可以values()在枚举上调用该方法。

for (Direction dir : Direction.values()) {
  // do what you want
}

This values()method is implicitly declared by the compiler. So it is not listed on Enumdoc.

values()方法由编译器隐式声明。所以它没有列在Enumdoc 上。

回答by dfa

All the constants of an enum type can be obtained by calling the implicit public static T[] values()method of that type:

枚举类型的所有常量都可以通过调用该public static T[] values()类型的隐式方法获得:

 for (Direction d : Direction.values()) {
     System.out.println(d);
 }

回答by toluju

You can do this as follows:

您可以按如下方式执行此操作:

for (Direction direction : EnumSet.allOf(Direction.class)) {
  // do stuff
}

回答by Tom Jefferys

If you don't care about the order this should work:

如果您不关心订单,这应该有效:

Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
    // do stuff
}

回答by user101884

for(Direction dir : Direction.values())
{

}

回答by akf

    for (Direction  d : Direction.values()) {
       //your code here   
    }

回答by akhil_mittal

Streams

Prior to Java 8

在 Java 8 之前

for (Direction dir : Direction.values()) {
            System.out.println(dir);
}

Java 8

爪哇 8

We can also make use of lambda and streams (Tutorial):

我们还可以使用 lambda 和流(教程):

Stream.of(Direction.values()).forEachOrdered(System.out::println);


Why forEachOrderedand not forEachwith streams ?

为什么forEachOrdered而不是forEach使用流?

The behaviour of forEachis explicitly nondeterministic where as the forEachOrderedperforms an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEachdoes not guarantee that the order would be kept.

的行为forEach是明确不确定的,其中当forEachOrdered为该流的每个元素执行操作时,如果该流具有定义的遇到顺序,则按照该流的遇到顺序。所以forEach不保证订单会被保留。

Also when working with streams (especially parallel ones) keep in mind the nature of streams. As per the doc:

此外,在使用流(尤其是并行流)时,请记住流的性质。根据文档

Stream pipeline results may be nondeterministic or incorrect if the behavioral parameters to the stream operations are stateful. A stateful lambda is one whose result depends on any state which might change during the execution of the stream pipeline.

如果流操作的行为参数是有状态的,则流管道结果可能是不确定的或不正确的。有状态 lambda 的结果取决于在流管道执行期间可能发生变化的任何状态。

Set<Integer> seen = Collections.synchronizedSet(new HashSet<>());
stream.parallel().map(e -> { if (seen.add(e)) return 0; else return e; })...

Here, if the mapping operation is performed in parallel, the results for the same input could vary from run to run, due to thread scheduling differences, whereas, with a stateless lambda expression the results would always be the same.

在这里,如果映射操作是并行执行的,由于线程调度差异,相同输入的结果可能会因运行而异,而对于无状态 lambda 表达式,结果将始终相同。

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

通常不鼓励流操作的行为参数的副作用,因为它们通常会导致无意中违反无状态要求,以及其他线程安全危险。

Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations.

流可能有也可能没有定义的相遇顺序。流是否具有遇到顺序取决于源和中间操作。

回答by Raghu K Nair

Java8

Java8

Stream.of(Direction.values()).forEach(System.out::println);

from Java5+

来自 Java5+

for ( Direction d: Direction.values()){
 System.out.println(d);
}

回答by Irazza

Try to use a for each

尝试为每个使用一个

for ( Direction direction : Direction.values()){
  System.out.println(direction.toString());
}

回答by NiVeR

More methods in java 8:

Java 8 中的更多方法:

Using EnumSetwith forEach

使用EnumSetforEach

EnumSet.allOf(Direction.class).forEach(...);

Using Arrays.asListwith forEach

使用Arrays.asListforEach

Arrays.asList(Direction.values()).forEach(...);