Video in progress

What's the difference between collect(Collectors.toList()) and stream.toList()?

Stream.toList() (Java 16+) returns an unmodifiable list. Collectors.toList() gives an ArrayList in practice, but its type and mutability are not guaranteed in the documentation.

📖 Answer

List<String> a = names.stream().map(String::trim).toList();
a.add("yangi");   // UnsupportedOperationException

List<String> b = names.stream().map(String::trim).collect(Collectors.toList());
b.add("yangi");   // works (an ArrayList in current JDKs)

Differences:

  • the result of toList() is immutable. add, remove, set throw an exception;
  • toList() allows null elements, unlike List.of;
  • toList() is shorter and a bit more economical.

Which to pick: if you only read the result, toList(). If you need to modify it later, don't rely on luck, say so explicitly: collect(Collectors.toCollection(ArrayList::new)).

There is also Collectors.toUnmodifiableList(), added in Java 10, but it throws an NPE if it sees a null.

Be careful when migrating old code to toList(): if someone later calls add on the result, it only fails at runtime.