java 如何在java8中将continue放在forEach循环中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38948817/
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
How to put continue in side forEach loop in java8
提问by Sunil Kumar Naik
How to write continue statement inside forEach loop in java 8.
如何在 Java 8 中的 forEach 循环中编写 continue 语句。
List<Integer> numList = Arrays.asList(10,21,31,40,59,60);
numList.forEach(x->{
if(x%2==0){
continue;
}
System.out.println(x);
});
The above code is giving compile time Error saying Continue outside of loop
上面的代码给出了编译时间错误说在循环外继续
List<Integer> numList = Arrays.asList(10,21,31,40,59,60);
LOOP:numList.forEach(x->{
if(x%2==0){
continue LOOP;
}
System.out.println(x);
});
The above code is giving compile time Error saying Undefined Label:LOOP
上面的代码给出了编译时间错误说未定义标签:循环
回答by Raman Sahasi
You can use return
. It won't stop the whole loop, instead, it will just stop the current iteration.
您可以使用return
. 它不会停止整个循环,相反,它只会停止当前的迭代。
Use it like this:
像这样使用它:
List<Integer> numList = Arrays.asList(10,21,31,40,59,60);
numList.forEach( x-> {
if( x%2 == 0) {
return; // only skips this iteration.
}
System.out.println(x);
});
回答by Leonardo Andrade
I think in this case, the best solution is filter the list before execute the println...
我认为在这种情况下,最好的解决方案是在执行 println 之前过滤列表...
exemple (I didn't test):
示例(我没有测试):
List<Integer> numList = Arrays.asList(10,21,31,40,59,60);
numList.stream().filter(x-> x%2 != 0).forEach(System.out::println);