CKTIS / Java
Collectors.toList: practical reference
Collectors.toList: practical reference: Collectors.toList accumulates stream elements into a List while making no promise about the concrete list type, serializability, thread safety, or mutability.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Collectors.toList(...)Collectors.toList accumulates stream elements into a List while making no promise about the concrete list type, serializability, thread safety, or mutability.
Use it when a mutable result is not contractually required and the collection must work on Java versions before Stream.toList.
Do not cast the result to ArrayList or rely on add succeeding. For a guaranteed unmodifiable result, use toUnmodifiableList or Stream.toList with its own null rules.
An empty stream returns an empty list. Encounter order is preserved for ordered streams; unordered sources need not acquire an order.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var list = java.util.stream.Stream.of("b", "a")
.collect(java.util.stream.Collectors.toList());
System.out.println(list);
}
}
Result
[b, a]
The example exercises the documented element in a small deterministic program and compares exact standard output.