Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.toList()

Gathers stream elements into an unmodifiable list.

Available since: Java 16

Syntax

default List<T> toList()

Return value

List<T>An unmodifiable list of the stream elements.

Examples

A short way to get a list:

void main() {
    List<Integer> squares = Stream.of(1, 2, 3).map(n -> n * n).toList();
    IO.println(squares);
    try {
        squares.add(16);
    } catch (UnsupportedOperationException e) {
        IO.println("unmodifiable");
    }
}

Output:

[1, 4, 9]
unmodifiable

Notes

The result cannot be changed — unlike collect(Collectors.toList()), which in practice returns an ArrayList. If you need to add to the list, use collect(Collectors.toCollection(ArrayList::new)) or new ArrayList<>(stream.toList()).

See also

Related recipes

In the tutorial

  • What a stream is — The Java Stream API — the source, intermediate and terminal operations, creating streams, lazy evaluation and why a stream can be used only once.

Thanks for reading!

Donate to the site — we work hard for you.