Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I count my stream size if I limit it by a predicate dependent on the input?

I want to make a stream with random numbers. As soon as the numbers fullfill a certain condition I want to now how many iterations was needed. So either I want to have the size of the stream or an Collection from which I can read then the size.

Here are my approaches:

random.ints(0, Integer.MAX_VALUE).anyMatch(a -> {return a < 20000;});

This gives me only the a boolean as soon as my condition is fullfilled.

random.ints(0, Integer.MAX_VALUE).filter(a -> a < 20000).limit(1).count();

And this returns obviously 1. But I want to have the size before I filtered my result. I further tried several things with a counting variable but since lambdas are capturing them effectifely final from outside I have an initialising problem.

Any help or hint is appreciated

like image 656
dbmongo Avatar asked Oct 17 '22 01:10

dbmongo


1 Answers

Java 9 has a feature to support that - takeWhile:

random.ints(0, Integer.MAX_VALUE).takeWhile(a -> a < 20000).count();
like image 194
Eran Avatar answered Oct 21 '22 04:10

Eran