Nic*_*yer 854 java enums for-loop
我有一个enumJava用于基数和中间方向:
public enum Direction {
NORTH,
NORTHEAST,
EAST,
SOUTHEAST,
SOUTH,
SOUTHWEST,
WEST,
NORTHWEST
}
Run Code Online (Sandbox Code Playgroud)
如何编写for循环遍历每个enum值的循环?
not*_*oop 1377
.values()您可以values()在枚举上调用该方法.
for (Direction dir : Direction.values()) {
// do what you want
}
Run Code Online (Sandbox Code Playgroud)
此values()方法由编译器隐式声明.所以它没有在Enumdoc上列出.
dfa*_*dfa 126
枚举值#():
for (Direction d : Direction.values()) {
System.out.println(d);
}
Run Code Online (Sandbox Code Playgroud)
tol*_*uju 61
你可以这样做:
for (Direction direction : EnumSet.allOf(Direction.class)) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
i_a*_*ero 43
for (Direction dir : Direction.values()) {
System.out.println(dir);
}
Run Code Online (Sandbox Code Playgroud)
我们也可以使用lambda和streams(教程):
Stream.of(Direction.values()).forEachOrdered(System.out::println);
Run Code Online (Sandbox Code Playgroud)
为什么forEachOrdered而不是forEach溪流?
如果流具有已定义的遭遇顺序,则在流的遭遇顺序中执行针对此流的每个元素的操作时,行为forEach明确是非确定性的forEachOrdered.所以forEach不保证订单会被保留.
在处理流(尤其是并行流)时,请记住流的本质.根据文件:
如果流操作的行为参数是有状态的,则流管道结果可能是不确定的或不正确的.有状态lambda是一个结果取决于在流管道执行期间可能发生变化的任何状态的lambda.
Set<Integer> seen = Collections.synchronizedSet(new HashSet<>());
stream.parallel().map(e -> { if (seen.add(e)) return 0; else return e; })...
Run Code Online (Sandbox Code Playgroud)
这里,如果映射操作是并行执行的,则由于线程调度差异,相同输入的结果可能因运行而不同,而对于无状态lambda表达式,结果将始终相同.
通常,不鼓励行为参数对流操作的副作用,因为它们通常会导致无意中违反无国籍要求以及其他线程安全危险.
流可能有也可能没有已定义的遭遇顺序.流是否具有遭遇顺序取决于源和中间操作.
Tom*_*rys 19
如果您不关心订单,这应该有效:
Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
akf*_*akf 18
for (Direction d : Direction.values()) {
//your code here
}
Run Code Online (Sandbox Code Playgroud)
Java8的
Stream.of(Direction.values()).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
从Java5 +
for ( Direction d: Direction.values()){
System.out.println(d);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
尝试对每个使用
for ( Direction direction : Direction.values()){
System.out.println(direction.toString());
}
Run Code Online (Sandbox Code Playgroud)
java 8中的更多方法:
EnumSet与使用forEachEnumSet.allOf(Direction.class).forEach(...);
Run Code Online (Sandbox Code Playgroud)
Arrays.asList与使用forEach Arrays.asList(Direction.values()).forEach(...);
Run Code Online (Sandbox Code Playgroud)