If you need this, you shouldn't use forEach, but one of the other methods available on streams; which one, depends on what your goal is.

For example, if the goal of this loop is to find the first element which matches some predicate:

Optional<SomeObject> result =
    someObjects.stream().filter(obj -> some_condition_met).findFirst();

(Note: This will not iterate the whole collection, because streams are lazily evaluated - it will stop at the first object that matches the condition).

If you just want to know if there's an element in the collection for which the condition is true, you could use anyMatch:

boolean result = someObjects.stream().anyMatch(obj -> some_condition_met);
Answer from Jesper on Stack Overflow
🌐
Brainly
brainly.com › computers and technology › high school › how can you break out of a stream's foreach loop in java 8?
[FREE] How can you break out of a stream's forEach loop in Java 8? - brainly.com
November 27, 2023 - To break out of a forEach loop in Java 8, you can use a traditional loop with a break statement, throw an exception (though it's not recommended), or convert the stream to an iterator for more control.
Discussions

java - how to break from a forEach method using lambda expression - Stack Overflow
Basically I have a list and its elements will be processed one by one until some condition is met. If that condition is met for any element, it should return true otherwise false. The method looks ... More on stackoverflow.com
🌐 stackoverflow.com
java - How to break from forEach loop when exception occur - Stack Overflow
The try catch block inside the forEach loop is because setAccount throwing SQLException. What I want to do is to stop(break) from the forEach loop in case there is an exception. More on stackoverflow.com
🌐 stackoverflow.com
terminate or break java 8 stream loop - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Closed 11 years ago. I have a java 8 stream loop with the following content: void matchSellOrder(Market market, Order sellOrder) { System.out.println("selling " + market.pair() + " : " + sellOrder); market.buyOrders() .stream() .filter(buyOrder -> buyOrder.price >= sellOrder.price) .sorted(BY_ASCENDING_PRICE) .forEach... More on stackoverflow.com
🌐 stackoverflow.com
May 12, 2021
Is there a way to exit a forEach loop early?
Some people will do literally anything to avoid learning to use simple built-in array methods. This problem would be solved simply and declaratively by using Array.prototype.find(). More on reddit.com
🌐 r/learnjavascript
18
7
August 2, 2019
🌐
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 - In this tutorial, we’re going to look at some mechanisms that allow us to simulate a break statement on a Stream.forEach operation. Let’s suppose we have a stream of String items and we want to process its elements as long as their lengths ...
🌐
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.
🌐
W3Schools
w3schools.com › java › java_break.asp
Java Break and Continue
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement. The break statement can also be used to jump out of a loop.
🌐
Javaprogramto
javaprogramto.com › 2020 › 05 › java-break-return-stream-foreach.html
How to Break or return from Java Stream forEach in Java 8 JavaProgramTo.com
May 13, 2020 - But this approach does not work when we try to replace this with the normal for a loop as below. package com.javaprogramto.java8.streams.foreach; import java.util.Arrays; import java.util.List; public class StreamForBreak { public static void main(String[] args) { List<String> list = Arrays.asList("one", "two", "three", "seven", "nine", "ten"); for (int i = 0; i < list.size(); i++) { if (list.get(i).length() > 3) { break; } System.out.println(list.get(i)); } } }
Find elsewhere
🌐
Coderanch
coderanch.com › t › 286701 › java › break-forEach-iteration
How to break c:forEach iteration? (JSP forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... I'm looking to the solution to break the c:forEach loop, similar to the below in pure Java: while(condition){ ...
🌐
TutorialsPoint
tutorialspoint.com › break-or-return-from-java-8-stream-foreach
Break or return from Java 8 stream forEach?
If you?re using Java 9 or above you can use the takeWhile method to process elements until some condition is met. names.stream() .takeWhile(name -> !name.equals("Bob")) .forEach(System.out::println); You can technically throw an exception in the case that you want to exit the forEach method, however this is not recommended. try { names.stream().forEach(name -> { if (name.equals("Bob")) { throw new RuntimeException("Exit loop"); } System.out.println(name); }); } catch (RuntimeException e) { // Handle exception }
Top answer
1 of 2
53

Stream.forEach is not a loop and it's not designed for being terminated using something like break. If the stream is a parallel stream the lambda body could be executed on different threads at the same time (not easy to break that and it could easily produce incorrect results).

Better use a iterator with a while loop:

Iterator<BuyOrderType> iter = market.buyOrders() // replace BuyOrderType with correct type here
            .stream()
            .filter(buyOrder -> buyOrder.price >= sellOrder.price)
            .sorted(BY_ASCENDING_PRICE).iterator();
while (iter.hasNext()) {
    BuyOrderType buyOrder = iter.next()  // replace BuyOrderType with correct type here
    double tradeVolume = Math.min(buyOrder.quantity, sellOrder.quantity);
    double price = buyOrder.price;

    buyOrder.quantity -= tradeVolume;
    sellOrder.quantity -= tradeVolume;

    Trade trade = new Trade.Builder(market, price, tradeVolume, Trade.Type.SELL).build();
    CommonUtil.convertToJSON(trade);

    if (sellOrder.quantity == 0) {
        System.out.println("order fulfilled");
        break;
    }
}
2 of 2
31

Well, there is no method to do this in the stream api, (as far as i know).

But if you really need it, you can use an Exception.

EDIT: For the people giving -1 to this answer I'm not advertising this as an approach one should follow, it's just an option for the cases where you need it, and it does answer the question.

public class BreakException extends RuntimeException {...}

try {
    market.buyOrders()
            .stream()
            .filter(buyOrder -> buyOrder.price >= sellOrder.price)
            .sorted(BY_ASCENDING_PRICE)
            .forEach((buyOrder) -> {
                double tradeVolume = Math.min(buyOrder.quantity, sellOrder.quantity);
                double price = buyOrder.price;

                buyOrder.quantity -= tradeVolume;
                sellOrder.quantity -= tradeVolume;

                Trade trade = new Trade.Builder(market, price, tradeVolume, Trade.Type.SELL).build();
                CommonUtil.convertToJSON(trade);

                if (sellOrder.quantity == 0) {
                    System.out.println("order fulfilled");
                    throw new BreakException()
                }
            });
} catch (BreakException e) {
    //Stoped
}
🌐
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
🌐
CodeAhoy
codeahoy.com › java › foreach-in-java
Complete Guide to Java 8 forEach | CodeAhoy
February 19, 2021 - The following results illustrate the benchmark when the Java HotSpot was run with the -client option. These benchmarks are interesting because they reveal an interesting point. When running in -server mode, the performance across all benchmarks is the same. But the forEach() method outperforms the traditional for loop for an array list when running in -client mode! We covered a lot of ground in this post. Let’s break ...
🌐
Reddit
reddit.com › r/learnjavascript › is there a way to exit a foreach loop early?
r/learnjavascript on Reddit: Is there a way to exit a forEach loop early?
August 2, 2019 -

One scenario where I choose a for loop over the forEach() method is when I want to break out of a loop early. Imagine I had a longer list of animals and as soon as I found one that matches some criteria, I want to perform some action. If I used forEach(), it would iterate over every single animal resulting in unnecessary iterations, potentially causing performance issues depending on how long the array is. With a for loop, you have the ability to break out early and stop the loop from continuing.

https://davidtang.io/2016/07/30/javascript-for-loop-vs-array-foreach.html

🌐
Java67
java67.com › 2016 › 01 › how-to-use-foreach-method-in-java-8-examples.html
10 Examples of forEach() method in Java 8 | Java67
Hello Umang, good point, I will probaby add that infomration when I update this article but for now, you can use the takeWhile method of Java 9 to break from forEach loop in Java like this takeWhile(n -> n.length() <=5) Delete
🌐
Medium
medium.com › @indiandevjourney › no-you-cant-break-a-foreach-loop-b4d7c9c5eef3
No, you can’t break a forEach loop! | by Shubham | Medium
June 28, 2019 - Before beginning if anyone of you ... it saves time and improves code readability. But do you know there is no way to break a forEach loop like a regular for loop....