00:00

Spliterator in Java

Last updated:

java.util.Spliterator<T> is the interface, added in Java 8, that supplies elements to a stream. The name combines split and iterator: like an Iterator it traverses elements, and it can also split itself into two parts so a parallel stream can process them on different threads. It also reports characteristics such as ORDERED and SIZED.

Every collection provides one through spliterator(). You write your own when you want to stream a custom data source, and you create a stream from it with StreamSupport.stream(). This tutorial covers the methods, characteristics, splitting and a custom implementation.

1. Syntax and Method Signatures

Spliterator.java (API)
// java.util.Spliterator<T> (Java 8)
boolean tryAdvance(Consumer<? super T> action)        // process one element, if any
default void forEachRemaining(Consumer<? super T> action)
Spliterator<T> trySplit()                             // split off a part, or null
long estimateSize()
default long getExactSizeIfKnown()                    // -1 if not SIZED
int characteristics()
default boolean hasCharacteristics(int characteristics)

// constants: ORDERED, DISTINCT, SORTED, SIZED, NONNULL, IMMUTABLE, CONCURRENT, SUBSIZED

// java.util.stream.StreamSupport (Java 8)
static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel)

tryAdvance() passes the next element to the Consumer and returns true, or returns false when there are no more. trySplit() hands over a prefix of the remaining elements as a new spliterator and keeps the rest.

2. How a Spliterator Works

A sequential stream calls the source spliterator's forEachRemaining(), or tryAdvance() repeatedly when short-circuiting. A parallel stream first calls trySplit() recursively to create tasks, using estimateSize() to decide when parts are small enough, then traverses each part on a worker thread.

Characteristics let the stream optimise: SIZED lets count() and toArray() know the size, SORTED lets sorted() be skipped, DISTINCT lets distinct() be skipped, and ORDERED tells the stream that encounter order matters.

trySplit() divides the work for parallel processing A spliterator over eight elements is split into two spliterators of four elements each. Each of those is split again into two of two elements. Four worker threads can then each traverse one part with tryAdvance or forEachRemaining. PART A PART B start elements 1 - 8 trySplit() 1 - 4 5 - 8 split again 1-2 | 3-4 5-6 | 7-8 traverse worker 1, worker 2 worker 3, worker 4
Figure 1: Each call to trySplit() hands off part of the elements. Balanced, cheap splits are what make arrays and ArrayList good parallel sources.

3. Java Examples

Example 1: Traversing with tryAdvance and forEachRemaining (Java 9+)

Process the first element of a queue of jobs separately, then the rest.

TraverseSpliterator.java
import java.util.List;
import java.util.Spliterator;

public class TraverseSpliterator {

    public static void main(String[] args) {
        List<String> jobs = List.of("backup", "index", "report", "cleanup");
        Spliterator<String> spliterator = jobs.spliterator();

        boolean hadFirst = spliterator.tryAdvance(job -> System.out.println("Priority job: " + job));
        System.out.println("tryAdvance returned " + hadFirst + ", remaining " + spliterator.estimateSize());

        spliterator.forEachRemaining(job -> System.out.println("Batch job: " + job));
        System.out.println("More? " + spliterator.tryAdvance(job -> { }));
    }
}
Output
Priority job: backup
tryAdvance returned true, remaining 3
Batch job: index
Batch job: report
Batch job: cleanup
More? false

How it works: tryAdvance() processes exactly one element, and forEachRemaining() processes the rest. When nothing is left, tryAdvance() returns false.

Example 2: Splitting an ArrayList (Java 9+)

Split the spliterator of a ten-element list and see how the elements are divided.

SplitArrayList.java
import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SplitArrayList {

    public static void main(String[] args) {
        List<Integer> ids = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toCollection(ArrayList::new));

        Spliterator<Integer> rest = ids.spliterator();
        Spliterator<Integer> prefix = rest.trySplit();

        List<Integer> a = new ArrayList<>();
        List<Integer> b = new ArrayList<>();
        prefix.forEachRemaining(a::add);
        rest.forEachRemaining(b::add);

        System.out.println("Split off: " + a);
        System.out.println("Kept:      " + b);
        System.out.println("SUBSIZED?  " + ids.spliterator().hasCharacteristics(Spliterator.SUBSIZED));
    }
}
Output
Split off: [1, 2, 3, 4, 5]
Kept:      [6, 7, 8, 9, 10]
SUBSIZED?  true

How it works: trySplit() returns the first half as a new spliterator and keeps the second half. SUBSIZED means the split parts also know their exact sizes, which helps parallel streams balance work.

Example 3: A custom spliterator for a data source (Java 16+)

Stream the pages of a paginated report, where each page is loaded on demand, by writing a spliterator.

PagedSpliteratorDemo.java
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class PagedSpliteratorDemo {

    // Pretends to fetch one page of rows from a server
    static List<String> fetchPage(int page) {
        return page < 3 ? List.of("row-" + page + "a", "row-" + page + "b") : List.of();
    }

    static class PagedSpliterator implements Spliterator<String> {
        private int page = 0;
        private List<String> current = List.of();
        private int index = 0;

        @Override
        public boolean tryAdvance(Consumer<? super String> action) {
            if (index == current.size()) {
                current = fetchPage(page++);
                index = 0;
                if (current.isEmpty()) {
                    return false;                    // no more pages
                }
            }
            action.accept(current.get(index++));
            return true;
        }

        @Override public Spliterator<String> trySplit() { return null; }          // cannot split
        @Override public long estimateSize() { return Long.MAX_VALUE; }           // unknown
        @Override public int characteristics() { return ORDERED | NONNULL; }
    }

    public static void main(String[] args) {
        Stream<String> rows = StreamSupport.stream(new PagedSpliterator(), false);
        System.out.println(rows.map(String::toUpperCase).toList());
    }
}
Output
[ROW-0A, ROW-0B, ROW-1A, ROW-1B, ROW-2A, ROW-2B]

How it works: Only tryAdvance() does real work; it loads the next page when the current one is used up. Returning null from trySplit() means the source cannot be split, which is fine for sequential streams. StreamSupport.stream() turns it into a full Stream.

Example 4: From an Iterator with Spliterators (Java 9+)

Stream a legacy Iterator without writing a spliterator class.

IteratorToStream.java
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.StreamSupport;

public class IteratorToStream {

    public static void main(String[] args) {
        Iterator<String> legacy = List.of("alpha", "beta", "gamma", "delta").iterator();

        long longNames = StreamSupport.stream(
                        Spliterators.spliteratorUnknownSize(legacy, Spliterator.ORDERED), false)
                .filter(name -> name.length() > 4)
                .count();

        System.out.println("Names longer than 4: " + longNames);
    }
}
Output
Names longer than 4: 3

How it works: Spliterators.spliteratorUnknownSize() adapts any Iterator. It splits poorly, by copying batches into arrays, so streams built this way gain little from parallel().

4. Real-World Use Cases

  • Custom sources: paginated APIs, database cursors, message batches or binary file records exposed as streams.
  • Library authors: providing efficient, splittable spliterators for custom collections.
  • Legacy code: turning Iterator or Enumeration based APIs into streams.
  • Performance tuning: understanding why some sources parallelise well and others do not.

5. Important Points

  • Not thread-safe: a spliterator is used by one thread at a time; splitting hands parts to other threads.
  • Late binding: JDK collection spliterators bind to the data at first use, not at creation.
  • Characteristics must be truthful; claiming SIZED or SORTED wrongly gives wrong results.
  • trySplit() may return null when splitting is impossible or not worthwhile.
  • Prefer existing tools: Stream.iterate(), Stream.generate() or Spliterators helpers often avoid a custom class.

6. Iterator vs Spliterator

AspectIteratorSpliterator
SinceJava 1.2Java 8
TraversalhasNext() + next()tryAdvance(), forEachRemaining()
Splitting for parallelismNotrySplit()
Size informationNoestimateSize()
CharacteristicsNoORDERED, SIZED, SORTED, ...
Used byfor-each loopsStreams

See Stream Pipeline Architecture for how the spliterator fits into the pipeline.

7. Common Mistakes and Best Practices

Reporting wrong characteristics

A spliterator that reports SIZED with a wrong estimateSize(), or SORTED for unsorted data, causes wrong count() or skipped sorting. Report only what is true.

Returning true without calling the action

Wrong
public boolean tryAdvance(Consumer<? super T> action) {
    if (skip(current)) return true;          // wrong: claims an element but sends none
    ...
}

tryAdvance() must call the action exactly once when it returns true. Loop internally to skip elements.

Other mistakes to avoid

  • Writing a custom spliterator where Stream.iterate() with a condition would do.
  • Using spliteratorUnknownSize() and expecting good parallel speed-ups.
  • Sharing one spliterator between threads.

8. Summary

  • A Spliterator supplies a stream's elements, can split for parallelism and reports characteristics.
  • tryAdvance() handles one element; forEachRemaining() the rest; trySplit() divides work.
  • Create streams from custom spliterators with StreamSupport.stream().
  • Characteristics must be accurate; they drive optimisations.

9. References