In Java 8 and later, spliterator() returns a Spliterator<E>: a "splittable iterator" over the elements of an ArrayList. It can visit elements one at a time with tryAdvance(), visit all remaining ones with forEachRemaining(), and hand part of its work to a new spliterator with trySplit().
Most programs never call it directly: list.stream() and parallel streams use it behind the scenes. Calling it yourself is useful for learning how streams divide work, or for writing your own stream sources.
An instance method of java.util.ArrayList (Java 1.2+): a resizable-array list with index access that allows null and duplicates and is not thread-safe. spliterator() was added in Java 8, together with streams.
Syntax
Get a spliterator, then advance, split, or drain it.
Java
Spliterator<String> sp = list.spliterator();
sp.tryAdvance(s -> System.out.println(s)); // first element
Spliterator<String> part = sp.trySplit(); // split off part of what is left
sp.forEachRemaining(System.out::println); // the rest of this part
Call
What it does
sp.tryAdvance(action)
Processes one element; returns false when none remain.
sp.forEachRemaining(action)
Processes every remaining element.
sp.trySplit()
Hands part of the elements to a new spliterator, or returns null.
sp.estimateSize()
Number of elements left (exact for an ArrayList).
ArrayList's spliterator is late-binding: it reads the list's size when you first use it, not when you create it. It is also fail-fast: structural changes made during traversal cause ConcurrentModificationException.
Library declarations
Java
// java.util.ArrayList<E>
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()
Parameters
Parameter
Description
None
spliterator() takes no parameters.
Return Value
Return Value
Description
Spliterator<E>
A new spliterator that reports the SIZED, SUBSIZED, and ORDERED characteristics.