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.
List<String> upper = names.stream().map(String::toUpperCase).toList();
Try it
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.
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
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()andList.copyOf(), which rejectnull. 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 totoList(). - 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.