Java HashSet spliterator() Method

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

Definition

In Java 8 and later, spliterator() returns a Spliterator<E> over the elements of a HashSet. A spliterator is like an iterator that can also split its remaining elements into two parts, which is how parallel streams divide the work.

You rarely need it directly, because set.stream() and set.parallelStream() use it for you. It is useful for learning how streams are built, and for custom traversal code.

An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety. spliterator() was added in Java 8, together with the Spliterator interface and streams.

Syntax

No arguments; the spliterator is then driven with its own methods.

Java
Set<Integer> nums = new HashSet<>(Arrays.asList(5, 1, 3));
Spliterator<Integer> sp = nums.spliterator();
sp.tryAdvance(n -> System.out.println(n));   // 1
CallWhat it does
sp.tryAdvance(action)Handles one element; false when none are left.
sp.forEachRemaining(action)Handles every remaining element in one call.
sp.trySplit()Hands back a new spliterator for part of the elements, or null.
sp.estimateSize()The number of elements left, as an estimate.

The default set.stream() is built on spliterator(), so everything a stream does with a HashSet starts here.

Library declarations
Java
// java.util.HashSet<E> (Java 8+), overrides Collection.spliterator()
public Spliterator<E> spliterator()

Parameters

ParameterDescription
Nonespliterator() takes no parameters.

Return Value

Return ValueDescription
Spliterator<E>A late-binding, fail-fast spliterator that reports SIZED and DISTINCT.

Compare with Similar Methods

Other ways to traverse a set:

MethodHow it differs
iterator()The simple one-element-at-a-time loop; it cannot split.
toArray()Copies everything into an array before you use it.
removeIf(test)Java 8 bulk removal that needs no manual traversal.

Java Examples

Example 1 — Step Through a Set with tryAdvance()

Handle one element per call until tryAdvance() returns false.

Java
import java.util.HashSet;
import java.util.Set;
import java.util.Spliterator;

public class HashSetSpliteratorDemo {
    public static void main(String[] args) {
        Set<Integer> numbers = new HashSet<>();
        numbers.add(5);
        numbers.add(1);
        numbers.add(3);

        Spliterator<Integer> sp = numbers.spliterator();
        while (sp.tryAdvance(n -> System.out.println("got " + n))) {
            // each successful call handled one element
        }
        boolean more = sp.tryAdvance(n -> System.out.println("never printed"));
        System.out.println("more left: " + more);
    }
}

How It Works

  1. One element per call. tryAdvance runs the lambda for the next element and returns true; the while loop repeats until it returns false.
  2. Hash order again. The numbers were added as 5, 1, 3, yet they are delivered by bucket position as 1, 3, 5.
  3. Exhausted. After the third element nothing is left, so the final tryAdvance returns false and never runs its lambda.
  4. Empty loop body. All the work happens inside the condition, which is why the braces only hold a comment.

Example 2 — Read the Size and Flags, Then Sum the Rest

Check the estimate and three characteristics, then add up every price with forEachRemaining().

Java
import java.util.HashSet;
import java.util.Set;
import java.util.Spliterator;

public class HashSetSpliteratorTraits {
    public static void main(String[] args) {
        Set<Integer> prices = new HashSet<>();
        prices.add(10);
        prices.add(20);
        prices.add(30);
        prices.add(40);
        prices.add(50);

        Spliterator<Integer> sp = prices.spliterator();
        System.out.println("estimate: " + sp.estimateSize());
        System.out.println("SIZED: " + sp.hasCharacteristics(Spliterator.SIZED));
        System.out.println("DISTINCT: " + sp.hasCharacteristics(Spliterator.DISTINCT));
        System.out.println("ORDERED: " + sp.hasCharacteristics(Spliterator.ORDERED));

        int[] total = {0};
        sp.forEachRemaining(price -> total[0] += price);
        System.out.println("total: " + total[0]);
    }
}

How It Works

  1. Exact size. Before any traversal the spliterator knows the set holds five elements, so estimateSize() is 5.
  2. SIZED and DISTINCT. A HashSet knows its size and never holds duplicates, so both flags are true.
  3. Not ORDERED. A hash table has no meaningful encounter order, so ORDERED is false.
  4. Accumulating in a lambda. A lambda cannot change a local int, so the sum goes into the one-element array total; 10 + 20 + 30 + 40 + 50 gives 150.

Example 3 — Split the Elements in Two with trySplit()

Ask the spliterator for half of the work, collect both halves, and count the elements.

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Spliterator;

public class HashSetSpliteratorSplit {
    public static void main(String[] args) {
        Set<Integer> numbers = new HashSet<>();
        for (int i = 1; i <= 10; i++) {
            numbers.add(i);
        }

        Spliterator<Integer> second = numbers.spliterator();
        Spliterator<Integer> first = second.trySplit();

        List<Integer> a = new ArrayList<>();
        List<Integer> b = new ArrayList<>();
        if (first != null) {
            first.forEachRemaining(a::add);
        }
        second.forEachRemaining(b::add);

        System.out.println("first part: " + a);
        System.out.println("second part: " + b);
        System.out.println("total: " + (a.size() + b.size()));
    }
}

How It Works

  1. Two spliterators. trySplit() detaches the first part of the work into a new spliterator, and the original keeps the rest.
  2. Split by bucket range. The default table has 16 buckets, so one part covers buckets 0 to 7 and the other 8 to 15; this is why 1 to 7 go together and 8 to 10 follow.
  3. Null check. trySplit() may return null when the data cannot be divided, so the code tests first before using it.
  4. Nothing lost or repeated. The two lists add up to all ten numbers, which is the guarantee a parallel stream relies on.

Frequently Asked Questions

It returns a Spliterator over the elements. A spliterator can step through elements one at a time or split them into two parts, which parallel streams use to share work.
Usually not. set.stream() and set.parallelStream() call it for you. Use it directly only for custom traversal or to learn how streams work.
An iterator only moves forward one element at a time. A spliterator can also split off part of the remaining elements with trySplit() and report characteristics such as SIZED and DISTINCT.
When the remaining elements cannot be divided any further, or are too few, trySplit() returns null and you keep traversing with the original spliterator.
No. A HashSet reports SIZED and DISTINCT but not ORDERED, because its elements have no guaranteed order.

Next: toArray()

Copy the elements into an array.

toArray() 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.

13 people found this page helpful