collect(Collectors.toList()) — creates a mutable ArrayList. toList() — creates an unmodifiable list (Java 16+). Think of collect(toList()) as handing the stream a flexible bag that you can add to later, while toList() hands you a sealed container that cannot be modified.
collect(Collectors.toList()):
ArrayList.1List<String> list = stream.collect(Collectors.toList());2list.add("new"); // OK — mutable3list.remove(0); // OK — mutable
toList():
UnsupportedOperationException.1List<String> list = stream.toList();2// list.add("new"); // UnsupportedOperationException
How they work under the hood:
List::add.Performance considerations:
When to use which:
1// CORRECT: use toList() for immutable results (most common)2List<String> immutableNames = names.stream()3 .filter(n -> n.length() > 3)4 .toList();56// CORRECT: use collect(toList()) when you need mutability7List<String> mutableNames = names.stream()8 .filter(n -> n.length() > 3)9 .collect(Collectors.toList());10mutableNames.add("extra"); // OK
Key difference: