Using return;
will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach
loop.
Try the following little program:
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
stringList.stream().forEach(str -> {
if (str.equals("b")) return; // only skips this iteration.
System.out.println(str);
});
}
Output:
a
c
Notice how the return;
is executed for the b
iteration, but c
prints on the following iteration just fine.
Why does this work?
The reason the behavior seems unintuitive at first is because we are used to the return
statement interrupting the execution of the whole method. So in this case, we expect the main
method execution as a whole to be halted.
However, what needs to be understood is that a lambda expression, such as:
str -> {
if (str.equals("b")) return;
System.out.println(str);
}
... really needs to be considered as its own distinct "method", completely separate from the main
method, despite it being conveniently located within it. So really, the return
statement only halts the execution of the lambda expression.
The second thing that needs to be understood is that:
stringList.stream().forEach()
... is really just a normal loop under the covers that executes the lambda expression for every iteration.
With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
for(String s : stringList) {
lambdaExpressionEquivalent(s);
}
}
private static void lambdaExpressionEquivalent(String str) {
if (str.equals("b")) {
return;
}
System.out.println(str);
}
With this "less magic" code equivalent, the scope of the return
statement becomes more apparent.
continue
would still move onto the next item without any functional changes anyway. – Urbannalelse
block. If there is nothing aftercontinue
, then drop the if block and the continue: they're useless. – Hokum