CodeBlanks Logo Icon CodeBlanks

Spliterator

Learn parallel iteration with Spliterator.

The Spliterator<T> interface

Spliterator<T> is an Iterator-like interface introduced in Java 8 designed for parallel traversal. tryAdvance(action) runs the action on the next element if one exists and returns true; otherwise returns false. forEachRemaining(action) processes all remaining elements at once.

trySplit() partitions the Spliterator into two parts to allow parallel processing; this is the basis of parallel streams. estimateSize() estimates the number of remaining elements.

Bulk processing with forEachRemaining

forEachRemaining(action) processes all remaining elements in one call. It is more concise than a while (sp.tryAdvance(action)) loop; Java still walks elements one by one behind the scenes but the code is shorter.

For example you take a Spliterator from a list and write sp.forEachRemaining(s -> System.out.println(s));. The -> token is a lambda expression; it will be detailed in the next group. Spliterator underpins the Stream API; you can also obtain one with list.stream().spliterator().

Practice Walk the list with a Spliterator

Declare List<String> names = new ArrayList<>();; add "Ayşe", "Alex", "Mehmet". Get Spliterator<String> sp = names.spliterator();. Print all elements in one call with sp.forEachRemaining(s -> System.out.println(s));.

Starter code

Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.Spliterator;

public class Main {
    public static void main(String[] args) {
        // Declare List<String>, add three names, get Spliterator, print with forEachRemaining

    }
}

Sample solution

Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.Spliterator;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Ayşe");
        names.add("Alex");
        names.add("Mehmet");
        Spliterator<String> sp = names.spliterator();
        sp.forEachRemaining(s -> System.out.println(s));
    }
}

Expected output

Ayşe
Alex
Mehmet

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the advance call

Question
while (sp.____(s -> System.out.println(s))) { }
Answer
while (sp.tryAdvance(s -> System.out.println(s))) { }

Explanation: tryAdvance runs the action on the next element if present.

2 What does Spliterator.trySplit do?

  • Deletes all elements
  • Returns only the first element
  • Returns an empty Spliterator
  • Splits the Spliterator in two Correct answer

Explanation: trySplit partitions the Spliterator into two for parallel processing.

3 Match the Spliterator methods

Term Meaning
tryAdvance Processes one element
forEachRemaining Bulk processes the rest
trySplit Splits in two
estimateSize Estimates remaining count

All lessons in Intermediate