Why return in Java 8 forEach Behaves Like continue and How to Properly Terminate the Loop
This article explains that using return inside Java 8’s forEach does not stop the surrounding method but merely skips the current iteration, similar to continue, and presents several solutions—including using a traditional foreach loop, break, return (not recommended), and throwing an exception—to correctly terminate the loop.
Hello everyone, I am Lei.
Scenario Demonstration
As shown in the image, we tried to terminate a for loop using return .
The execution result is displayed below:
Only the element "Zhao Liu" is not printed, while the subsequent array elements are still processed.
In other words, the keyword return here works like the continue keyword in a normal for loop.
Reason Analysis
In a regular for loop, break is used to end the loop early, and continue ends the current iteration and proceeds to the next one.
Additionally, using return inside a normal for loop not only ends the loop body but also exits the entire method that contains the loop.
In Java 8’s forEach() , break and continue are not allowed, and return no longer carries its original meaning.
Let’s Look at the Source Code
forEach() is fundamentally a method, not a loop construct; ending a method’s execution naturally uses return .
Java’s forEach() is very similar to JavaScript’s forEach() ; you may explore the comparison at the end of the article.
Java is not omnipotent—don’t disparage it.
Solutions
Solution 1: Use the traditional foreach loop
Developers familiar with Eclipse know that typing foreach and pressing Alt+/ will trigger a code template.
The screenshot shows the proper format of a true foreach loop.
In IntelliJ IDEA, the same shortcut does not work; you need to invoke the template manually.
Method 1: break
Note
Method 2: return (not recommended)
Solution 2: Throw an exception
Normally, to end a method’s execution you use return .
In practice, many unexpected situations (e.g., a NullPointerException) cause early termination; you can also achieve the same effect by throwing a custom exception to stop forEach() .
If this approach feels unfriendly, you can wrap it in another layer.
This completes the solution.
Be careful that the forEach() body does not contain other code that might throw exceptions identical to the manually thrown one; otherwise you may unintentionally swallow genuine errors.
Source: blog.csdn.net/weixin_39597399
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.