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]
unmodifiableNotes
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
- Collectors.toList() — A collector that puts stream elements into a list.
- Stream.collect() — Gathers stream elements into a collection, a string or another structure.
- Collection.stream() — Creates a stream over the elements of a collection.
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.