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?
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();
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.