Video in progress
What is the difference between Stream.toList(), Collectors.toList() and Collectors.toUnmodifiableList(), and what can you break when migrating code?
mutable / null element — collect(Collectors.toList()): yes (an ArrayList in practice) / allowed; stream.toList(): no / allowed; collect(Collectors.toUnmodifiableList()): no / NPE
📖 Answer
| mutable | null element | |
|---|---|---|
collect(Collectors.toList()) |
yes (an ArrayList in practice) |
allowed |
stream.toList() |
no | allowed |
collect(Collectors.toUnmodifiableList()) |
no | NPE |
IDEs now suggest replacing collect(Collectors.toList()) with toList(). In an automatic refactoring, this is where the bug slips in:
List<String> names = users.stream().map(User::name).toList();
// ... further down, in another method
names.add("admin"); // UnsupportedOperationException, only at runtime
On one team this replacement was made in 200 places, and then two or three spots that keep filling up the list crashed on prod. The compiler doesn't help, because the type is still List<String>.
For a safe migration:
- check whether the result is modified later: look at the usages;
- if you need to modify the list, say so explicitly:
collect(Collectors.toCollection(ArrayList::new)); - add test cases that try to modify the result.
The null difference matters too: if you move to toUnmodifiableList() and the data happens to contain a null, you get another runtime error. toList() lets null through silently, which only pushes the error further down.
My habit: in new code, toList() when I need an immutable result and toCollection(ArrayList::new) when I need a mutable one. I don't use Collectors.toList(), because it doesn't show the intent.
Sign up to mark studied questions and save your progress.