在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建议改善上述解决方案一样,您可以将IntStream
与findFirst
结合使用:
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