What would be a good use-case scenario for the Spliterator
class in Java 8?

- 3,870
- 4
- 27
- 53

- 953
- 1
- 12
- 29
-
Spliterator, not SplitIterator. :-) – C. K. Young Jul 09 '14 at 18:27
-
I found these questions http://stackoverflow.com/questions/23114015/why-does-iterablet-not-provide-stream-and-parallelstream-methods?lq=1 and http://stackoverflow.com/questions/20075860/making-an-efficient-java-8-sorted-spliterator-from-an-array which seem relevant for a Spliterator. – EpicPandaForce Oct 14 '14 at 10:43
-
1Streams are built from Spliterators. So, every time you would like to create a Stream from a collection, you would need to provide a Spliterator. http://docs.oracle.com/javase/8/docs/api/java/util/stream/StreamSupport.html – JB Nizet Oct 14 '14 at 11:38
3 Answers
Normally, an application developer would not consume the Spliterator
API directly. But if you are providing an API, and implement your own collection-like class, you can implement Spliterator
to adapt your collection to the Stream
API. This supports a functional approach, parallel processing, and other features.
For example, I wrote a utility to enumerate IP addresses in a network, specified by CIDR notation. It's not really a collection; that is, it doesn't carry list of all of the addresses in memory at once, only the network number and netmask. But by exposing a Spliterator
, it can be easily adapted to a Stream
. (Each Spliterator
just tracks the current IP address and maximum address in its share of the network.)
Another example from the core Java runtime is DirectoryStream
for traversing the file system.

- 265,237
- 58
- 395
- 493
Use case example: "Converts iterator to stream"
public static <T> Stream<T> iteratorToFiniteStream(final Iterator<T> iterator) {
final Iterable<T> iterable = () -> iterator;
return StreamSupport.stream(iterable.spliterator(), false);
}

- 3,320
- 1
- 34
- 37
Spliterator
is an extension of the timeless Iterator
class that allows for splitting of a stream of objects to iterate over (Stream
works by collecting the operations before iterating).
I cannot think of any times when the average developer would have to work with Spliterator
. The Collection
and Collections
APIs are incredibly rich in Java 8, and in most cases you'd be better off using a vanilla Collection
subclass instead of building your own Stream
interface.
An example of when you might want to use Spliterator
might be a library for graphs using a linked data structure over which the standard Spliterator
/stream()
is undefined.

- 3,870
- 4
- 27
- 53
-
-
1@erickson I did not mean inheritance. It continues the _concept_ of `Iterator`. – Simon Kuang Feb 10 '15 at 19:02