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

Viewed 121

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?

4 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();

Even though you have mentioned Java 8, if you are going to use Java 9 or above and need to know the number of times the loop was executed, then do as follows:

long count = IntStream.range(1,6)
                      .takeWhile(i -> !doSomething()) // loop continued till doSomething is true
                      .count();

takeWhile was introduced in Java 9.

Plain old approach:

while(i <= n && !doSomething()) { 
    // do something here
    i++;
}

Pretty clear and concise.

This is tidier:

for (int i = 0; i < 5 && !doSomething(); i++);
Related