Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Stream#limit return fewer elements than expected?

If the Stream s below has at least n elements, what are the situations where the stream sLimit may have less than n elements, if any?

Stream sLimit = s.limit(n);

Reason for the question: in this answer, I read that:

Despite the appearances, using limit(10) doesn't necessarily result in a SIZED stream with exactly 10 elements -- it might have fewer.

like image 489
assylias Avatar asked Dec 20 '22 07:12

assylias


1 Answers

You misunderstood the statement. If the Stream has at least n elements and you invoke limit(n) on it, it will have exactly n elements but the Stream implementation might not be aware of it and hence have a less than optimal performance.

In contrast, certain Stream sources (Spliterators) know for sure that they have a fixed size, e.g. when creating a Stream for an array or an IntStream via IntStream.range. They can be optimized better than a Stream with a limit(n).

When you create a parallel Stream via Stream.generate(MyClass::new).limit(10), the constructor will still be invoked sequentially and only follow-up operations might run in parallel. In contrast, when using IntStream.range(0, n).mapToObj(i -> new MyClass()), the entire Stream operation, including the constructor calls, can run in parallel.

like image 182
Holger Avatar answered Dec 21 '22 21:12

Holger