krosenvold krosenvold - 2 years ago 70
Java Question

How to get size of underlying stream when count and limit is used?

I have a rather large, and I would like to extract a subset of this stream as well as get the size of the entire source stream. I would like to retain the stream behavior, so I do not want to collect this stream to a List. Is this possible ?

Stream src = ....
Stream subsetStream = src.offset(x).limit(y);
long totalLengthOfSrc = ??

Answer Source

Count is a terminal operation, meaning that the stream is considered consumed afterwards - so it's impossible to use limit on it. I don't think this is possible using the straightforward stream API, but you could do it like this:

final AtomicLong length = new AtomicLong(0);
Stream subsetStream = src.filter(a -> length.getAndIncrement() < y);

length could be a regular long instead, if you're certain that src isn't a parallel stream. If src is a parallel stream whose length is larger than y, then you might not get the first y elements but some y elements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download