您当前的位置: 首页 > 

石头wang

暂无认证

  • 0浏览

    0关注

    295博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

关于 stream( ) 或 forEach() 为什么不能用如continue和break,如何替代

石头wang 发布时间:2021-12-22 21:30:00 ,浏览量:0

关于 stream( ) 或 forEach() 为什么不能用如continue和break,如何替代

结论:使用不了continue和break,会编译失败。在forEach里头使用return就相当于continue。

那有人会问,怎么break呢?

背景

比如

// 用 forEach 替代
arrayList.forEach(x ->  {
    if (x.equals("8")) {
        //continue; // 不支持,提示 Continue outside of loop
        //break;// 不支持,提示 Break outside switch or loop
        return;// 其实 return 就是相当于传统的for循环的continue
    }
    System.out.println("处理其他业务逻辑--->" + x);
});
补充
// 这种写法是有问题,contain为true也不会退出,即使找到了匹配的也会继续遍历,效率低
arrayList.forEach(x ->  {
    boolean contain = false;
    if (x.equals("8")) {
        return;
    }

    if (contain) {
        System.out.println("contain");
        return;
    }

    System.out.println(x);
});


// 正确的写法是(类似的写法)
boolean contain = arrayList.stream().anyMatch(x -> "8".equals(x));
String s = arrayList.stream().filter(x -> "8".equals(x)).findFirst().orElse(null);
关注
打赏
1663722529
查看更多评论
立即登录/注册

微信扫码登录

0.0369s