如何在Java Stream API中重写"while(true)"



这个Java代码可以被Stream API重写吗?

while (true) {
...
if (isTrue()) break;
}
private boolean isTrue() {
...

这是可怕的代码,没有理由使用它。流是常规循环的附加工具,它们不能替代for,尤其是while循环。

// If you use this code seriously somewhere, I will find you
IntStream.generate(() -> 0)
.peek(i -> {
// Any custom logic
System.out.println(i);
})
.noneMatch(i -> isTrue());

代码无限生成零,在流中查看以执行自定义逻辑,然后在noneMatch计算结果为true时停止。

以上相当于问题中的代码,可以写得更简洁

do {
// custom logic
} while(!isTrue());

使用 Stream API 循环时无法替换或重写。流 API 从流中读取值。while (true)不会从任何流中读取数据。它只是一个无限循环。

最新更新