用break重写循环到lambda

我有一个计数器周期:

List<Mt4Report> history = ...
int counter = 0;
for (Mt4Report item : history) {
    if (item.getProfit().compareTo(BigDecimal.ZERO) < 0) {
        counter++;
    } else {
        break;
    }
}

我如何使用lambda表达式.findFirst().ifPresent写同样的想法,但保留break语句?

tmroybq 回答:用break重写循环到lambda

在Java-9及更高版本中,您可以使用takeWhile方法:

int counter = (int) history.stream()
        .takeWhile(item -> item.getProfit().compareTo(BigDecimal.ZERO) < 0)
        .count();

对于Java-8解决方案,您可以研究this answer中提供的takeWhile的自定义实现。另一方面,使用indexOf的效率较低的实现可能是执行:

int count = history.stream()
        .filter(ite -> ite.getProfit().compareTo(BigDecimal.ZERO) >= 0)
        .findFirst()
        .map(history::indexOf)
        .orElse(history.size());

正如Holger建议改善上述解决方案一样,您可以将IntStreamfindFirst结合使用:

int count = IntStream.range(0,history.size())
                     .filter(ix -> history.get(ix).getProfit() .compareTo(BigDecimal.ZERO) >= 0)
                     .findFirst()
                     .orElse(history.size());
,

根据Java 8,没有直接解决此问题的方法,该问题基本上是使用Stream停止Predicate
在Java 9中,您拥有takeWhile()方法,但是在Java 8中,没有这样的事情。
请参阅this post

本文链接:https://www.f2er.com/3142563.html

大家都在问