背景
在项目中发抽用lambda的forEach,对于普通的for循环我们可以通过break等关键字提前跳出for循环,但是在lambda中的forEach使用时发现并不能终止for循环。
结论
anyMatch来替代forEach以达到提前结束的效果
解决
问题复现
在lambda的forEach中break关键字不可使用,而return的作用并不是终止for循环,而是continue的作用。
例子:
List<String> list2 = new ArrayList<String>() {{
this.add("ccc");
this.add("ccc");
this.add("aaa");
this.add("bbb");
}};
list2.stream().forEach(s -> {
if ("aaa".equals(s)) {
return;
}
System.out.println(s);
});
//返回结果
//ccc
//ccc
//bbb
上面例子可以看出return只是跳过了当前循环,并没有结束for循环。
方案解决
如果只是想满足既定条件后提前结束for循环,那我们可以用lambda的anyMatch来替代forEach以达到提前结束的效果。
anyMatch()里接收一个返回值为boolean类型的表达式,只要返回true就会终止循环,这样可以将业务逻辑写在返回判断结果前。
例子:
List<String> list2 = new ArrayList<String>() {{
this.add("ccc");
this.add("ccc");
this.add("aaa");
this.add("bbb");
}};
list2.stream().anyMatch(s -> {
System.out.println(s);
return "aaa".equals(s);
});
//输出结果
//ccc
//ccc
//aaa
由结果可看出bbb并没有打印,for循环提前终止。