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

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> squares = nums.stream()
                .map(n -> n * n)
                .collect(Collectors.toList());
        System.out.println(squares);
        // Returned list type is ArrayList; mutation is allowed.
        squares.add(36);
        System.out.println(squares);
    }
}

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.