Video in progress
What is a Spliterator and how do its characteristics affect how a stream works?
A Spliterator is the mechanism by which a stream pulls elements from a source and splits the source into parts. Its flags (SIZED, ORDERED, DISTINCT, SORTED, IMMUTABLE and others) let the stream optimize: skip unnecessary work, allocate an exactly sized array, and behave well in parallel.
📖 Answer
Every stream has a Spliterator underneath. Its main methods:
tryAdvance(action): hand over one element;forEachRemaining(action): the rest all at once;trySplit(): split off a part of the source into a new spliterator (for parallel);estimateSize()andcharacteristics().
What the flags give you in practice:
SIZED:count()answers without traversing the elements, andtoArray()allocates an array of the right size once;SORTED:sorted()doesn't sort again if the order is the same;DISTINCT:distinct()does nothing (for example from aHashSet);ORDERED: order must be preserved;unordered()removes it, and in paralleldistinctandlimitget cheaper;SUBSIZED: the sizes of the split-off parts are known too; that's why a parallelArrayList/array splits well.
Spliterator<String> sp = new ArrayList<>(List.of("a", "b")).spliterator();
sp.hasCharacteristics(Spliterator.SIZED); // true
sp.hasCharacteristics(Spliterator.ORDERED); // true
new HashSet<>(List.of(1, 2)).spliterator()
.hasCharacteristics(Spliterator.DISTINCT); // true
If you write a spliterator for your own source (say, a paginated API), start from Spliterators.AbstractSpliterator and write only tryAdvance. Set the flags carefully: a wrong SIZED or DISTINCT leads the stream to a wrong result, because it trusts you.
Streams built from a LinkedList or an Iterator split badly, and that is often where a parallel stream's slowness comes from.
Sign up to mark studied questions and save your progress.