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
AtomicIntegerfor initialisation, peek in stream to increment counter, but it won't work the same in parallel streamanyMatchreturns true,peekwould be done beforeanyMatchto have thecountAtomicIntegerandpeekas a counter is a hack and should be avoided. Streams were designed to avoid side-effects and this approach goes against this core principle. Unless streams are an absolute necessity, you're better off switching to Java 9 or using a traditionalfor-each-indexloop.