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

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

关于 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);

相关文章

世界杯3次扩军的历史进程(历史、影响与变革)
篮球体育比分365

世界杯3次扩军的历史进程(历史、影响与变革)

⌛ 07-04 👁️‍🗨️ 5967
你,为什么创业?
bt365体育开户

你,为什么创业?

⌛ 07-11 👁️‍🗨️ 4398
牖启的解释及意思
bt365体育开户

牖启的解释及意思

⌛ 07-02 👁️‍🗨️ 727