如何在foreach中进行break或者continue?
List<String> colors = new ArrayList<>(Arrays.asList("white", "black", "red", "blue", "green"));
//当遇到颜色时,结束整个循环
for (String color : colors) {
if (color.equals("red")) {
break;
}
System.out.println(color);
}
//当遇到蓝颜色时,跳过本次循环
for (String color : colors) {
if (color.equals("blue")) {
continue;
}
System.out.println(color);
}
List<String> colors = new ArrayList<>(Arrays.asList("white", "black", "red", "blue", "green"));
colors.forEach(color -> {
if (color.equals("blue")) {
return;
}
System.out.println(color);
});
//输出如下:
white
black
red
green
//首先需要自定义一个异常
public class BreakException extends RuntimeException {}
//使用该异常实现break的语义
List<String> colors = new ArrayList<>(Arrays.asList("white", "black", "red", "blue", "green"));
try {
colors.forEach(color -> {
if (color.equals("blue")) {
throw new BreakException();
}
System.out.println(color);
});
} catch (BreakException e) {
System.out.println("foreach while break");
}
//输出如下
white
black
red
foreach while break
但是在实践中,并不推荐使用这种折中的方式去实现break或者continue的语义,即不应该使用foreach。而是应该根据程序的意图,去选择stream中提供的其他方法来达到目的。
//在colors集合中,寻找blue
List<String> colors = new ArrayList<>(Arrays.asList("white", "black", "red", "blue", "green"));
Optional<String> target = colors.stream().filter(color -> color.equals("blue")).findFirst();
String targetColor = target.get();
System.out.println(targetColor);
//输出如下
blue