lambda中的forEach如何跳出循环

发布时间 2023-04-04 16:10:19作者: 欢乐豆123

lambda中的forEach如何跳出循环

      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

 

 参考链接:https://www.cnblogs.com/keeya/p/11306254.html