Java Snippet

Stream toList Collector

Difficulty: Easy

Collecting a stream into a `List` is the most common terminal operation in modern Java. This snippet shows the three idiomatic options: the legacy `Collectors.toList()`, the unmodifiable `Collectors.toUnmodifiableList()` (Java 10+), and the convenient `Stream.toList()` shortcut (Java 16+). Pick the unmodifiable variant for return values to prevent caller mutation.

Code Snippets
/

Stream toList Collector

Stream toList Collector

Collecting a stream into a `List` is the most common terminal operation in modern Java. This snippet shows the three idiomatic options: the legacy `Collectors.toList()`, the unmodifiable `Collectors.toUnmodifiableList()` (Java 10+), and the convenient `Stream.toList()` shortcut (Java 16+). Pick the unmodifiable variant for return values to prevent caller mutation.

Java
Easy
3 snippets
java-streams
java-collections
implementation

196 views

2

Collectors.toList() returns a mutable ArrayList carrying the stream's results. It is the workhorse collector that has shipped since Java 8 and is still useful when you need to keep adding to or sorting the list afterwards. The lambda n -> n * n is mapped over the stream, then materialised into a list. Don't return this list from a public method without copying or wrapping with Collections.unmodifiableList(...) if callers should not mutate it.