With Java-9 and above, you can use takeWhile
approach as :
int counter = (int) history.stream()
.takeWhile(item -> item.getProfit().compareTo(BigDecimal.ZERO) < 0)
.count();
For the Java-8 solution, you can look into a custom implementation of takeWhile
provided in this answer. On the other hand, a less efficient implementation with the use of indexOf
could be to perform:
int count = history.stream()
.filter(ite -> ite.getProfit().compareTo(BigDecimal.ZERO) >= 0)
.findFirst()
.map(history::indexOf)
.orElse(history.size());
As Holger suggested to improve the above solution, you can make use of the IntStream
with findFirst
:
int count = IntStream.range(0, history.size())
.filter(ix -> history.get(ix).getProfit() .compareTo(BigDecimal.ZERO) >= 0)
.findFirst()
.orElse(history.size());