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.

Answer from sstan on Stack Overflow
Top answer
1 of 5
480

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.

2 of 5
9

Another solution: go through a filter with your inverted conditions : Example :

if(subscribtion.isOnce() && subscribtion.isCalled()){
                continue;
}

can be replaced with

.filter(s -> !(s.isOnce() && s.isCalled()))

The most straightforward approach seem to be using "return;" though.

🌐
Baeldung
baeldung.com › home › java › java collections › the difference between collection.stream().foreach() and collection.foreach()
The Difference Between stream().forEach() and forEach() | Baeldung
September 17, 2025 - If we want to use functional-style Java, we can also use forEach(). ... In this simple case, it doesn’t make a difference which forEach() we use. Collection.forEach() uses the collection’s iterator (if one is specified), so the processing order of the items is defined. In contrast, the processing order of Collection.stream().forEach() is undefined.
Discussions

java - How to put continue in side forEach loop in java8 - Stack Overflow
How to write continue statement inside forEach loop in java 8. More on stackoverflow.com
🌐 stackoverflow.com
Break or return from Java 8 stream forEach? - Stack Overflow
However I can imagine some useful ... of forEach() or so, for which using exception is not bad practice. I have added a paragraph to my answer to be clear. 2016-06-02T22:07:32.297Z+00:00 ... I think this is a fine solution. After searching Google for "java exceptions" and other searches with a few more words like "best practices" or "unchecked", etc., I see there is controversy over how to use exceptions. I used this solution in my code because the stream was performing ... More on stackoverflow.com
🌐 stackoverflow.com
How to do it in Java 8 stream api foreach continue or break - Stack Overflow
I have following code where I want to break or continue in the for each loop:- List (); Map rowMap2 = new More on stackoverflow.com
🌐 stackoverflow.com
What does 'return' do inside a forEach loop? (or for any kind of loop, are there differences in behaviour?)
The bottom line here is that, in the situation you presented (using Array#forEach), the return statement has no value and can be omitted without changing the effect of your code. To understand why, you need to understand how forEach works. Fortunately, we can do it ourselves and even more fortunately it's the most simple of the array methods to implement. Rather than modify the JavaScript array, let's create a wrapper of our own let myArrayType = { values: [1,2,3,4,5], forEach: function(functionToCall){ for(v of this.values){ functionToCall(v); } } } myArrayType.forEach(item => console.log(item)); You'll see that, because our lambda function is wrapped in the outer function call on the forEach method on our object, returning a value from it doesn't do anything. The outer function would need to be designed for the inner function to return a value. forEach isn't designed that way. On the other hand, map is designed for the inner function to return a value. The implementation of map is nearly identical except for the fact it expects a value to be returned from the lambda: let myArrayType = { values: [1,2,3,4,5], forEach: function(functionToCall){ for(v of this.values){ functionToCall(v); } }, map:function(functionToCall){ const mappedValues = []; for(v of this.values){ const mappedValue = functionToCall(v); mappedValues.push(mappedValue); } return mappedValues; } } At this line const mappedValue = functionToCall(v); we are assigning the result of the lambda to a variable, so we can append it to the return array. So, the message here is that forEach doesn't need a return statement in the lambda (it's literally just a waste of typing), but map (and other array methods) do - it's down to the way that these methods are designed. Just to cap off this point, I'm only talking above about the array methods. In a situation like this: function processArray(ary){ for(v of ary){ return v; } } The return statement would cause the whole function to return at the first element of the array. This is different to returning from a function that is passed to forEach because the lambda function is wrapped inside another function. More on reddit.com
🌐 r/learnprogramming
15
8
April 27, 2022
🌐
TutorialsPoint
tutorialspoint.com › break-or-return-from-java-8-stream-foreach
Break or return from Java 8 stream forEach?
Like return inside lambda exits the lambda expression but not the forEach or the enclosing method. Attempting to use break or continue will result in a compilation error: names.stream().forEach(name -> { if (name.equals("Bob")) { break; // Compilation error } });
🌐
W3Docs
w3docs.com › java
Break or return from Java 8 stream forEach?
However, since forEach() is a terminal operation and is not intended to be used as a loop, it is generally better to use a different method such as findFirst() or anyMatch() if you only need to find a single element in the stream. Here's an example of how you can use findFirst() to find the first even number in a stream and return from the operation: List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Integer result = numbers.stream() .filter(n -> n % 2 == 0) .findFirst() .orElse(null); System.out.println(result); // prints 2
🌐
Baeldung
baeldung.com › home › java › java streams › how to break from java stream foreach
How to Break from Java Stream forEach | Baeldung
January 25, 2024 - The Java 8 streams library and its forEach method allow us to write that code in a clean, declarative manner. While this is similar to loops, we are missing the equivalent of the break statement to abort iteration. A stream can be very long, or potentially infinite, and if we have no reason to continue ...
🌐
Quora
quora.com › Are-there-any-advantages-of-using-forEach-from-Java-8-instead-of-a-forEach-loop-from-Java-5-Java-development
Are there any advantages of using forEach(..) from Java 8 instead of a forEach loop from Java 5 (Java development)? - Quora
Answer (1 of 4): Yes, there are distinct advantages. However, to get those advantages, your code needs to use some of the other functionality of Java 8. I was in a rather complicated but also very interesting talk at a conference, where one of the Java just-in-time compiler developers spoke abou...
Find elsewhere
🌐
Codemia
codemia.io › knowledge-hub › path › move_to_next_item_using_java_8_foreach_loop_in_stream
Move to next item using Java 8 foreach loop in stream
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
GeeksforGeeks
geeksforgeeks.org › java › foreach-loop-vs-stream-foreach-vs-parallel-stream-foreach
foreach() loop vs Stream foreach() vs Parallel Stream foreach() - GeeksforGeeks
July 12, 2025 - For example, if we want to print only the first 2 values of any collection or array and then we want to return any value, it can be done in foreach loop in Java. The code below is for printing the 2nd element of an array. ... public class GFG { public static String frechlop(String[] geek) { int count = 0; for (String var : geek) { if (count == 1) return var; count++; } return ""; } public static void main(String[] args) throws Exception { String[] arr1 = { "Geeks", "For", "Geeks" }; String secelt = frechlop(arr1); System.out.println(secelt); } } ... Lambda operator is used: In stream().forEach(), lambdas are used and thus operations on variables outside the loop are not allowed.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java stream foreach()
Java Stream forEach() with Examples - HowToDoInJava
March 14, 2022 - Stream forEach(action) method is used to iterate over all the elements of this stream and to perform an action on each element of the stream.
🌐
Codemia
codemia.io › knowledge-hub › path › break_or_return_from_java_8_stream_foreach
Break or return from Java 8 stream forEach?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
Tutorialspoint
tutorialspoint.com › java › java_continue_statement.htm
Java - continue Statement
The statement can be used in any loop control structure to skip the current iteration and jump to the next one. In a loop, it immediately transfers control to the update statement, while in a or loop, it jumps directly to the Boolean expression for
🌐
W3Schools
w3schools.com › java › java_break.asp
Java Break and Continue
The break statement can also be used to jump out of a loop. ... The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
🌐
Baeldung
baeldung.com › home › java › core java › guide to the java foreach loop
Guide to the Java forEach Loop | Baeldung
June 17, 2025 - The article is an example-heavy introduction of the possibilities and operations offered by the Java 8 Stream API. ... In Java, the Collection interface has Iterable as its super interface. This interface has a new API starting with Java 8: ... Simply put, the Javadoc of forEach states that it “performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.”
🌐
Java67
java67.com › 2016 › 01 › how-to-use-foreach-method-in-java-8-examples.html
10 Examples of forEach() method in Java 8 | Java67
You can read more about that in the Collections to Streams in Java 8 Using the Lambda Expressions course on Pluralsight, which provides an in-depth explanation of new Java 8 features. So far you have both basic and advanced examples of using the forEach() method, first with simply iterating over each element and then along with using the filter() method, Let's see one more example of the forEach() method along with the map() function, which is another key functionality of Stream API.
🌐
Stack Overflow
stackoverflow.com › questions › 51654187 › how-to-do-it-in-java-8-stream-api-foreach-continue-or-break
How to do it in Java 8 stream api foreach continue or break - Stack Overflow
List<Map<String, Object>> dataSource = new ArrayList<>(); Map<String, Object> rowMap2 = new LinkedHashMap<>(); dataSource.stream().forEach(item -> { Map<String, Object> rowMap2 = new LinkedHashMap<>(); if(item.get("Security").toString().equals("SECURITIES")){ rowMap2 = item; for(Map.Entry<String, Object> entry : rowMap2.entrySet()){ if(entry.getKey().equalsIgnoreCase("Security")){ entry.getKey().replace(entry.getKey(), mainType); } } dataSource2.add(rowMap2); // I want to continu here.
🌐
Mkyong
mkyong.com › home › java8 › java 8 foreach examples
Java 8 forEach examples - Mkyong.com
December 4, 2020 - In Java 8, we can use the new forEach to loop or iterate a Map, List, Set, or Stream.