Stream.forEach不是循环,也并非设计为使用终止
break。如果流是并行流,则lambda主体可以同时在不同的线程上执行(这不容易打破,并且很容易产生错误的结果)。
最好使用带有while循环的迭代器:
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; }}


