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
使用抛出异常的方式实现break的语义
//首先需要自定义一个异常
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