I am having the old style while loop like below:
int i = 1, n = 5;
while(i <= n) {
if (doSomething()) {
break;
}
i++;
}
Is it possible to do it in a good way in Java 8?
You can do it using IntStream and findFirst short-circuiting terminal operation. And when ever doSomething() method returns true the execution of stream pipeline will be terminated
IntStream.range(1,5)
.filter(i -> doSomething())
.findFirst();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With