krosenvold
krosenvold

Reputation: 77141

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

I have a rather large java.util.stream.Stream, 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 = ??

Upvotes: 2

Views: 1295

Answers (2)

D Levant
D Levant

Reputation: 116

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.

Upvotes: 3

m. vokhm
m. vokhm

Reputation: 699

In general - yes, it is possible. It depends on what Stream exactly do you use. Stream is just an interface, while your object is always an instance of a certain class. FileInputStream, for example, has associated FileChannel that can be accessed via getChannel() method and has the size() method.

Upvotes: -1

Related Questions