Is it possible to calculate the size of my stream if I restrict it to an input dependent predicate?

I want to create a stream with random numbers. As soon as numbers fill a certain condition, I want how many times iterations have been. Therefore, either I want to have the size of the stream, or a collection from which I can read the size.

Here are my approaches:

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

This only gives me a boolean once my condition is filled.

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

And this returns, obviously, 1. But I want to have size before filtering my result. I also tried several things with variable counting, but since lambdas capture them effectively from the outside, I have a problem with initialization.

Any help or hint appreciated

+5
source share
3 answers

Java 9 has a function that supports this: takeWhile :

 random.ints(0, Integer.MAX_VALUE).takeWhile(a -> a < 20000).count(); 
+3
source

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); 

Print

 in stream : 1466689339 in result : 1466689339 in stream : 1588320574 in result : 1588320574 in stream : 1621482181 in result : 1621482181 in stream : -2140739741 3 
0
source

There is no Stream.takeWhile() in Java 8, but you can easily get around this with iterator() :

 public static int countWhile(IntStream stream, IntPredicate predicate) { PrimitiveIterator.OfInt iterator = stream.iterator(); int i = 0; while (predicate.test(iterator.nextInt())) { i++; } return i; } 
0
source

Source: https://habr.com/ru/post/1274149/


All Articles