Custom Spliterator Feeds Stream API

Adapt a custom index-range source to the Stream API by implementing tryAdvance, trySplit, estimateSize, and characteristics on a small Spliterator.

JavaData Integrity

Code

snippet
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.StreamSupport;

public class WordSource implements Spliterator<String> {

    private final List<String> words;
    private int pos;
    private final int end;

    public WordSource(List<String> words, int pos, int end) {
        this.words = words;
        this.pos = pos;
        this.end = end;
    }
    @Override
    public boolean tryAdvance(Consumer<? super String> action) {
        if (pos >= end) {
            return false;
        }
        action.accept(words.get(pos++));
        return true;
    }
    @Override
    public Spliterator<String> trySplit() {
        int remaining = end - pos;
        if (remaining < 2) {
            return null; // 剩余太少不再拆分
        }
        int mid = pos + remaining / 2;
        Spliterator<String> leftHalf = new WordSource(words, pos, mid);
        pos = mid; // 本体保留右半段
        return leftHalf;
    }

    @Override
    public long estimateSize() {
        return end - pos;
    }
    @Override
    public int characteristics() {
        return ORDERED | SIZED | SUBSIZED | IMMUTABLE | NONNULL;
    }

    public static void main(String[] args) {
        List<String> tokens = List.of("orders", "billing", "auth", "search", "report", "cache");

        // 任何 Spliterator 都能接进 Stream API
        long count = StreamSupport.stream(new WordSource(tokens, 0, tokens.size()), false).count();
        System.out.println("streamed count: " + count);

        // trySplit 手动对半拆:两个半段各自独立遍历
        WordSource full = new WordSource(tokens, 0, tokens.size());
        Spliterator<String> left = full.trySplit();
        left.forEachRemaining(w -> System.out.println("left: " + w));
        full.forEachRemaining(w -> System.out.println("right: " + w));
    }
}

The Spliterator surface

WordSource implements the four core methods: tryAdvance feeds one element to a Consumer and returns false when pos reaches end; trySplit halves the remaining range (returning null below two elements); estimateSize reports end - pos; characteristics declares ORDERED | SIZED | SUBSIZED | IMMUTABLE | NONNULL.

Feeding the Stream API

StreamSupport.stream(new WordSource(tokens, 0, tokens.size()), false) turns the source into a sequential Stream whose count() prints streamed count: 6 — no intermediate collection is needed.

Manual half split

The demo also calls trySplit by hand: the left half (orders, billing, auth) prints under left:, the retained right half (search, report, cache) under right:, showing that both halves iterate independently after the split.

Interactive Tools for This Topic

FAQ

What does returning null from trySplit mean?
That the remaining range is too small to split (fewer than two elements); the caller should keep traversing this spliterator directly.
Why declare SIZED and SUBSIZED?
They promise estimateSize is exact and that any split keeps that property, letting stream pipelines skip resizing heuristics.