Stream ToList Unmodifiable Shortcut
Stream.toList returns an unmodifiable list while Collectors.toList stays mutable, so defensive copies depend on which terminal operator you pick.
Code
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TerminalLists {
public static void main(String[] args) {
List<String> viaToList = Stream.of("a", "b").toList();
// the list Stream.toList returns is unmodifiable: appending throws
try {
viaToList.add("c");
} catch (UnsupportedOperationException e) {
System.out.println("toList add rejected");
}
// Collectors.toList returns a mutable list; older code may rely on that
List<String> viaCollector = Stream.of("a", "b").collect(Collectors.toList());
viaCollector.add("c");
System.out.println("collector list: " + viaCollector);
// toList accepts null elements; zero tolerance needs Collectors.toUnmodifiableList
List<String> withNull = Stream.of("a", null).toList();
System.out.println("null accepted: " + withNull.size());
}
}What the demo compares
Stream.of(“a”, “b”).toList() produces an unmodifiable list: add throws UnsupportedOperationException and the demo prints toList add rejected. The same stream through Collectors.toList() stays mutable; the following add succeeds and the printed list holds three items.
Null tolerance is the surprise: toList accepts null elements, so a stream containing null collects fine and the size prints 2. Code that must reject nulls needs Collectors.toUnmodifiableList instead, since toList optimizes for immutability, not validation.
Points to remember
- toList has no Collector overhead; it is a direct terminal op.
- Mutability of the collector result is an API contract some callers depend on.
Interactive Tools for This Topic
FAQ
- Which terminal op returns a mutable list?
- Collectors.toList(); its result accepts add, as the demo shows right after the toList result rejected the same call with UnsupportedOperationException.
Report a problem with this exampleOpens a pre-filled issue on GitHub.