增强for、lambda for、stream 遍历List 结束方法 or 跳过循环本次循环

增强for、lambda for、stream 遍历List 结束方法 or 跳过循环本次循环

        List<Integer> list = Arrays.asList(1, 2, 3, 4);
        System.out.println("forEach");
        list.forEach(e -> {
            if (e == 2) {
                return; // 结束本次循环
            }
            System.out.println(e);
        });

        System.out.println("stream().anyMatch");
        list.stream().anyMatch(e -> {
            if (e == 2) {
                return false; // 结束本次循环
//                return true; // 结束方法
            }
            System.out.println(e);
            return false;
        });

        System.out.println("for");
        for (Integer i : list) {
            if (i == 2) {
                continue; // 结束本次循环
//                return; // 结束方法
            }
            System.out.println(i);
        }

  

 

posted @ 2020-08-28 10:20  唐胜伟  阅读(3830)  评论(0编辑  收藏  举报