Java TreeSet spliterator() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java 8+, spliterator() returns a Spliterator<E> over sorted elements, powering stream() and parallelStream().

A top-level TreeSet spliterator is late-binding, fail-fast, and reports SIZED, DISTINCT, SORTED, and ORDERED.

An instance method of java.util.TreeSet (Java 8+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe. Requires Java 8 or newer.

Syntax

Obtain a spliterator to step one element at a time, drain the rest, or split work.

Java
Spliterator<String> sp = set.spliterator();
sp.tryAdvance(s -> System.out.println("first: " + s));
sp.forEachRemaining(s -> System.out.println("next: " + s));
CallWhat it does
sp.tryAdvance(action)Processes one element; returns false when none remain.
sp.forEachRemaining(action)Processes all remaining elements in sorted order.
sp.trySplit()Splits off a prefix spliterator, or returns null.
sp.getComparator()Returns null for natural order, or the custom Comparator.

Because it is late-binding, it binds to the tree on first traversal, size check, or split rather than at creation.

Library declarations
Java
// java.util.TreeSet<E>  (since Java 8)
public Spliterator<E> spliterator()

// java.util.Spliterator<T>
boolean tryAdvance(Consumer<? super T> action)
void forEachRemaining(Consumer<? super T> action)
Spliterator<T> trySplit()
long estimateSize()
int characteristics()
Comparator<? super T> getComparator()

Parameters

ParameterDescription
Nonespliterator() takes no parameters.

Return Value

Return ValueDescription
Spliterator<E>A late-binding, fail-fast spliterator reporting SIZED | DISTINCT | SORTED | ORDERED.

Compare with Similar Methods

Ways to consume or split a TreeSet:

MethodHow it differs
iterator()Simpler single-threaded traversal supporting it.remove().
descendingIterator()Single-pass traversal from largest to smallest.
set.stream()Builds a stream pipeline using spliterator() automatically.
ArrayList.spliterator()Reports SUBSIZED too and splits exactly in half; not SORTED or DISTINCT.

Java Examples

Example 1 — Step With tryAdvance(), Check estimateSize(), and Drain Remaining

Inspect exact size on a top-level spliterator, pull one SKU with tryAdvance(), then process the rest with forEachRemaining().

Java
import java.util.Arrays;
import java.util.Spliterator;
import java.util.TreeSet;

public class TreeSetSpliteratorAdvance {
    public static void main(String[] args) {
        TreeSet<String> skus = new TreeSet<>(Arrays.asList("SKU-30", "SKU-10", "SKU-40", "SKU-20"));
        Spliterator<String> sp = skus.spliterator();

        System.out.println("initial estimateSize: " + sp.estimateSize());
        sp.tryAdvance(s -> System.out.println("handled first: " + s));
        sp.forEachRemaining(s -> System.out.println("remaining: " + s));
        System.out.println("more? " + sp.tryAdvance(s -> System.out.println(s)));
    }
}

How It Works

  1. Exact top-level size. Before splitting, sp.estimateSize() returns 4, matching skus.size().
  2. Consume one sorted item. tryAdvance() runs the lambda on SKU-10 alone and advances past it.
  3. Drain remaining items. forEachRemaining() visits SKU-20, SKU-30, and SKU-40 in order before exhausting the spliterator.

Example 2 — Check SORTED, DISTINCT, Late Binding, and getComparator()

Create a spliterator before adding elements, inspect its characteristic flags, and compare getComparator() on natural vs custom sets.

Java
import java.util.Comparator;
import java.util.Spliterator;
import java.util.TreeSet;

public class TreeSetSpliteratorTraits {
    public static void main(String[] args) {
        TreeSet<Integer> nums = new TreeSet<>();
        Spliterator<Integer> sp = nums.spliterator();

        nums.add(20);
        nums.add(10);

        System.out.println("SORTED:   " + sp.hasCharacteristics(Spliterator.SORTED));
        System.out.println("DISTINCT: " + sp.hasCharacteristics(Spliterator.DISTINCT));
        System.out.println("SIZED:    " + sp.hasCharacteristics(Spliterator.SIZED));
        System.out.println("ORDERED:  " + sp.hasCharacteristics(Spliterator.ORDERED));
        System.out.println("late-bound size: " + sp.estimateSize());
        System.out.println("natural getComparator: " + sp.getComparator());

        TreeSet<Integer> desc = new TreeSet<>(Comparator.reverseOrder());
        desc.add(5);
        System.out.println("custom comparator non-null? " + (desc.spliterator().getComparator() != null));
    }
}

How It Works

  1. Late binding in action. Elements 20 and 10 were added after creating sp, yet estimateSize() binds on first use and reports 2.
  2. Four TreeSet flags. Top-level TreeSet spliterators always advertise SORTED, DISTINCT, SIZED, and ORDERED.
  3. getComparator() matches set. Natural ordering returns null, whereas reverseOrder() returns a non-null Comparator.

Example 3 — Split a TreeSet Spliterator With trySplit()

Split a six-element spliterator into two parts, drain both parts independently, and combine them back into a sorted set.

Java
import java.util.Arrays;
import java.util.Spliterator;
import java.util.TreeSet;

public class TreeSetSpliteratorSplit {
    public static void main(String[] args) {
        TreeSet<Integer> ids = new TreeSet<>(Arrays.asList(10, 20, 30, 40, 50, 60));
        Spliterator<Integer> right = ids.spliterator();
        Spliterator<Integer> left = right.trySplit();

        System.out.println("split succeeded? " + (left != null));
        System.out.println("after split SIZED? " + right.hasCharacteristics(Spliterator.SIZED));

        TreeSet<Integer> merged = new TreeSet<>();
        if (left != null) {
            left.forEachRemaining(merged::add);
        }
        right.forEachRemaining(merged::add);
        System.out.println("covered all 6? " + merged.equals(ids) + " -> " + merged);
    }
}

How It Works

  1. Split at the internal root. trySplit() hands the lower portion to left and keeps the upper portion in right.
  2. SIZED flag cleared. Because red-black tree halves are not counted exactly in O(1), child spliterators report SIZED = false.
  3. Complete partition guaranteed. Draining both halves covers all six numbers without missing or duplicating any element.

Frequently Asked Questions

Top-level TreeSet spliterators report SIZED, DISTINCT, SORTED, and ORDERED. After trySplit(), child spliterators drop SIZED.
null for natural ordering, or the custom Comparator passed at creation.
Yes. It binds to the tree contents on first traversal, size check, or split rather than at creation.
Yes. trySplit() splits the red-black tree around its root so parallelStream() can process subranges across threads.
Java 8 (JDK 1.8), alongside java.util.Spliterator and the Streams API.

Next: subSet()

Get a live view of elements between a lower bound and an upper bound.

subSet() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful