terminate or break java 8 stream loop [duplicate]

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
            .filter(buyOrder -> buyOrder.price >= sellOrder.price)
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();

    if (sellOrder.quantity == 0) {
        System.out.println("order fulfilled");

Leave a Comment