Can this Java code be re-written by Stream API?
while (true) {
...
if (isTrue()) break;
}
private boolean isTrue() {
...
Can this Java code be re-written by Stream API?
while (true) {
...
if (isTrue()) break;
}
private boolean isTrue() {
...
This is horrible code, there's no reason ever to use this. Streams are an additional tool to regular loops, they're not a replacement for for and especially while loops.
// 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());
The code generates zeroes infinitely, peeks in the stream to perform custom logic, then stops when noneMatch evaluates to true.
The above is equivalent to the code in the question, which can be written far more succinctly as
do {
// custom logic
} while(!isTrue());
You cannot replace or rewrite while loop with Stream API. Stream API reads values from Stream. while (true) is not reading data from any stream. It is simply a infinite loop.