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

98
December 18, 2017, at 11:51 PM

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

Answer 1

Java 9 has a feature to support that - takeWhile:

random.ints(0, Integer.MAX_VALUE).takeWhile(a -> a < 20000).count();
Answer 2

You can try takeWhile from this project

Example :

IntStream intStream = new Random().ints();
        Stream<Integer> result = StreamUtils.takeWhile(intStream.boxed().peek(i->System.out.println("in stream : " + i)), i -> i > 2000);
        long count = result.peek(i->System.out.println("in result : " + i))
                .count();
        System.out.println(count);

Prints:

in stream : 1466689339
in result : 1466689339
in stream : 1588320574
in result : 1588320574
in stream : 1621482181
in result : 1621482181
in stream : -2140739741
3
READ ALSO
Creating a chat view with a scroll pane and dynamical loading

Creating a chat view with a scroll pane and dynamical loading

I am currently working on a xmpp chat application with JavaFX and want to create a chat view which is inspired by Telegram

99
Java Spring Relational-Mapping with Map datatype

Java Spring Relational-Mapping with Map datatype

Iam trying to include some fields of datatype Map in my table that is created in a H2-databaseThe fields "text" and "validationGroup" are working correctly and i can see them in the database but I want the fields "statementMap" and "fields" to be mapped...

123
Rxjava chain more than one request

Rxjava chain more than one request

I am new in concept of RxJavaI would like to chain some calls:

109
AKKA (java) - future - OnComplete.onComplete - is not called

AKKA (java) - future - OnComplete.onComplete - is not called

OnCompleteonComplete is not called (selected code inside MyActor was executed)

105