lambda中的forEach如何跳出循环
前提
在Java8中的forEach()中,"break"或"continue"是不被允许使用的,而return的意思也不是原来return代表的含义了。forEach(),说到底是一个方法,而不是循环体,结束一个方法的执行自然是用return。
\1. 在Java8中直接写 continue/break
由上图可知:在Java8中直接写 continue会提示Continue outside of loop,break则会提示Break outside switch or loop,continue/break 需要在循环外执行
\2. lambda中使用return
1 public static void main(String[] args) {
2 List<String> list = Arrays.asList("test", "abc", "student", "345", "javaTest");
3
4 System.out.println("测试forEach:return>>>>>");
5
6 list.stream().forEach(e -> {
7 if (e.length() >= 5) {
8 return;
9 }
10 System.out.println(e);
11 });
12 }
13
14 // 测试结果:
15 // test
16 // abc
17 // 345
由此可以看出:lambda表达式forEach中使用return相当于普通for循环中的continue
\3. lambda中forEach跳出循环的解决方案
1) 方式一:抛出异常
1 public static void main(String[] args) {
2 List<String> list = Arrays.asList("test", "abc", "student", "345", "javaTest");
3
4 try {
5 list.stream().forEach(e -> {
6 if (e.length() >= 5) {
7 throw new RuntimeException();
8 }
9 System.out.println(e);
10 });
11 } catch (Exception e) {
12 }
13 }
14
15 // 测试结果
16 // test
17 // abc
这里不太建议使用抛出异常的方式,因为还需要注意一个地方:
要确保forEach()方法体内不能有其它代码可能会抛出的异常与自己手动抛出并捕获的异常一样;否则,当真正该因异常导致代码终止的时候,因为咱们手动捕获了并且没做任何处理,反而弄巧成拙。
2)方式二:anyMatch
我们不妨换一种思路,跳出的前提肯定是满足了某一条件的,可以所以使用anyMatch方法
1 public static void main(String[] args) {
2 List<String> list = Arrays.asList("test", "abc", "student", "345", "javaTest");
3
4 // anyMatch接收到的表达式值为true时,就会终止循环
5 list.stream().anyMatch(e -> {
6 System.out.println(e);
7 return e.length() >= 5;
8 });
9 }
10
11 // 测试结果
12 // test
13 // abc
14 // student
3)方式三 filter中的findAny
同理,采用类似的思路可以使用filter()方法,思路是一样的,其中findAny表示只要找到满足的条件时停止
1 public static void main(String[] args) {
2 List<String> list = Arrays.asList("test", "abc", "student", "345", "javaTest");
3
4 // 其中findAny表示只要找到满足的条件时停止
5 list.stream().filter(e -> {
6 System.out.println(e);
7 return e.length() >= 5;
8 }).findAny();
9 }
10
11 // 测试结果
12 // test
13 // abc
14 // student
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2021-11-04 throw和throws有什么不同?