Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collection.spliterator — traversing collection elements

Collection.spliterator() returns an object for traversing collection elements and potentially partitioning the work. Learn the default implementation, size characteristics, and limitations around modification and concurrency.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

default Spliterator<E> spliterator()

Collection.spliterator() returns a Spliterator<E> over the collection's elements. tryAdvance(action) processes one element and returns true, or returns false when exhausted. forEachRemaining(action) processes the remaining elements. trySplit() may partition off work as another spliterator or return null; calling it does not start threads.

The default Collection implementation uses an Iterator, is late-binding, and inherits its fail-fast properties. It reports SIZED and SUBSIZED: the initial size is exact without structural modification, and spliterators produced by splitting also have known sizes. Concrete collections may override this method; check their documentation.

Late binding occurs on the first traversal, split, or estimated-size query. It does not imply a snapshot or thread safety. Fail-fast detection is best-effort error detection, not synchronization. Unless the implementation explicitly guarantees otherwise, do not modify the source during traversal.

The default stream() and parallelStream() use the collection's spliterator; splitting capability does not guarantee a speedup. The example uses an ordered List, so it prints elements in list order. The Collection interface alone does not guarantee that order.

Examples

import java.util.Collection;
import java.util.List;
import java.util.Spliterator;

public class Main {
    public static void main(String[] args) {
        Collection<Integer> values = List.of(10, 20, 30);
        Spliterator<Integer> cursor = values.spliterator();

        System.out.println(cursor.getExactSizeIfKnown());
        cursor.tryAdvance(System.out::println);
        cursor.forEachRemaining(System.out::println);
        System.out.println(cursor.tryAdvance(System.out::println));
    }
}

Result

3
10
20
30
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources