CKTIS / Java
Stream.toList: practical reference
Stream.toList: practical reference: Stream.toList() is a terminal operation since Java 16 that accumulates elements in encounter order into an unmodifiable List.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Stream.toList(...)Stream.toList() is a terminal operation since Java 16 that accumulates elements in encounter order into an unmodifiable List.
Use it for a result snapshot that needs no later changes; when a specific mutable implementation is required, use Collectors.toCollection.
Every mutator on the result throws UnsupportedOperationException; assume neither an implementation type, serializability, nor identity of its potentially value-based instance.
An empty stream yields an empty list and null elements are retained, so its null contract differs from Collectors.toUnmodifiableList.
toList retains the null element, so the first line is [a, null]; add throws UnsupportedOperationException and the catch prints unmodifiable.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var result = java.util.stream.Stream.of("a", null).toList();
System.out.println(result);
try { result.add("b"); } catch (UnsupportedOperationException error) { System.out.println("unmodifiable"); }
}
}
Result
[a, null] unmodifiable
toList retains the null element, so the first line is [a, null]; add throws UnsupportedOperationException and the catch prints unmodifiable.