Home Java TreeSet Methods spliterator() Java TreeSet spliterator() Method 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.
Spliterator<String> sp = set.spliterator();
sp.tryAdvance(s -> System.out.println("first: " + s));
sp.forEachRemaining(s -> System.out.println("next: " + s)); Call What 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.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 Parameter Description None spliterator() takes no parameters.
Return Value Return Value Description Spliterator<E>A late-binding, fail-fast spliterator reporting SIZED | DISTINCT | SORTED | ORDERED.
Compare with Similar Methods Ways to consume or split a TreeSet:
Method How 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 1. tryAdvance and forEachRemaining 2. Characteristics and late binding 3. Partition with trySplit 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().
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)));
}
} initial estimateSize: 4
handled first: SKU-10
remaining: SKU-20
remaining: SKU-30
remaining: SKU-40
more? false How It Works Exact top-level size. Before splitting, sp.estimateSize() returns 4, matching skus.size().Consume one sorted item. tryAdvance() runs the lambda on SKU-10 alone and advances past it.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.
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));
}
} SORTED: true
DISTINCT: true
SIZED: true
ORDERED: true
late-bound size: 2
natural getComparator: null
custom comparator non-null? true How It Works Late binding in action. Elements 20 and 10 were added after creating sp, yet estimateSize() binds on first use and reports 2.Four TreeSet flags. Top-level TreeSet spliterators always advertise SORTED, DISTINCT, SIZED, and ORDERED.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.
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);
}
} split succeeded? true
after split SIZED? false
covered all 6? true -> [10, 20, 30, 40, 50, 60] How It Works Split at the internal root. trySplit() hands the lower portion to left and keeps the upper portion in right.SIZED flag cleared. Because red-black tree halves are not counted exactly in O(1), child spliterators report SIZED = false.Complete partition guaranteed. Draining both halves covers all six numbers without missing or duplicating any element.Frequently Asked Questions Which characteristics does TreeSet spliterator() report? Top-level TreeSet spliterators report SIZED, DISTINCT, SORTED, and ORDERED. After trySplit(), child spliterators drop SIZED.
What does spliterator().getComparator() return for a TreeSet? null for natural ordering, or the custom Comparator passed at creation.
Is TreeSet spliterator() late-binding? Yes. It binds to the tree contents on first traversal, size check, or split rather than at creation.
Does TreeSet spliterator() support parallel streams? Yes. trySplit() splits the red-black tree around its root so parallelStream() can process subranges across threads.
Which Java version added TreeSet spliterator()? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion