I read some questions how to create a finite Stream
(
Finite generated Stream in Java - how to create one?, How do streams stop?).
The answers suggested to implement a Spliterator
. The Spliterator
would implement the logic how to and which element to provide as next (tryAdvance
). But there are two other non-default methods trySplit
and estimateSize()
which I would have to implement.
The JavaDoc of Spliterator
says:
An object for traversing and partitioning elements of a source. The source of elements covered by a
Spliterator
could be, for example, an array, aCollection
, an IO channel, or a generator function. ... TheSpliterator
API was designed to support efficient parallel traversal in addition to sequential traversal, by supporting decomposition as well as single-element iteration. ...
On the other hand I could implement the logic how to advance to the next element around a Stream.Builder
and bypass a Spliterator
. On every advance I would call accept
or add
and at the end build
. So it looks quite simple.
What does the JavaDoc say?
A mutable builder for a
Stream
. This allows the creation of aStream
by generating elements individually and adding them to theBuilder
(without the copying overhead that comes from using anArrayList
as a temporary buffer.)
Using StreamSupport.stream
I can use a Spliterator
to obtain a Stream
. And also a Builder
will provide a Stream
.
When should / could I use a Stream.Builder
?
Only if a Spliterator
wouldn't be more efficient (for instance because the source cannot be partitioned and its size cannot be estimated)?