gpt4 book ai didi

java - 终止或中断 java 8 流循环

转载 作者:IT老高 更新时间:2023-10-28 21:17:55 25 4
gpt4 key购买 nike

我有一个包含以下内容的 java 8 流循环:

    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((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");
// break loop there
}
});
}

满足某些条件时如何跳出循环?无论如何,关闭流的正确方法是什么?

更新

我误用了流技术,假设它是一个循环,它不是为此而设计的。这是我最终使用下面提供的答案的代码:

        List<Order> applicableSortedBuyOrders = market.buyOrders()
.stream()
.filter(buyOrder -> buyOrder.price >= sellOrder.price)
.sorted(BY_ASCENDING_PRICE)
.collect(toList());

for(Order buyOrder : applicableSortedBuyOrders){
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.printAsJSON(trade);

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

最佳答案

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;
}
}

关于java - 终止或中断 java 8 流循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23996454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com