Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

Java Stream.toList() method

Reference for Java 16 Stream.toList(): collect a stream into an unmodifiable list, how it differs from Collectors.toList(), and null handling.

Stream.toList(), added in Java 16, is a terminal operation that collects the elements into a List in encounter order. The list it returns is unmodifiable: add, remove, set and sort all throw UnsupportedOperationException.

It is shorthand for collect(Collectors.toList()) in most code, but with a different guarantee: Collectors.toList() makes no promise about mutability (in practice an ArrayList), while toList() promises it cannot be modified. Unlike List.of(), it allows null elements.

Java
List<String> upper = names.stream().map(String::toUpperCase).toList();

Try it

Java Collecting and trying to modify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Nulls and copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
default List<T> toList()

No parameters.

Returns: an unmodifiable List<T> with the stream's elements in encounter order.

Usage notes

  • Unmodifiable: every mutator throws UnsupportedOperationException. The list is not a view; it holds its own elements.
  • Nulls allowed: this differs from List.of() and List.copyOf(), which reject null. The result still prints and iterates normally.
  • Not identical to Collectors.toList(): that collector gives no guarantee of type or mutability, and existing code that later adds to the result will break if switched to toList().
  • Immutable but not deeply: the elements themselves can still be mutable objects.
  • Sets and maps: use Collectors.toSet()/toMap() for those; Collectors.toUnmodifiableList() also rejects nulls.
  • Version: requires Java 16 or later. On Java 8 to 15 use collect(Collectors.toList()).
  • Cost: O(n); the stream is consumed and cannot be reused.
  • Parallel streams: encounter order is preserved.