Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java 8 provide a good way to repeat a function based on specific condition?

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?

like image 920
It's me Avatar asked Aug 24 '26 19:08

It's me


1 Answers

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();
like image 84
Deadpool Avatar answered Aug 27 '26 08:08

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!