Unmodifiable collectors
Collect directly to an unmodifiable list with stream.toList().
Code Comparison
โ Java 8
List<String> list = stream.collect(
Collectors.collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
)
);
โ Java 16+
List<String> list = stream.toList();
See a problem with this code? Let us know.
Why the modern way wins
Shortest yet
stream.toList() needs no collect() or Collectors import at all.
Immutable
Result cannot be modified โ no accidental mutations.
Readable
Reads naturally as the terminal step of any stream pipeline.
Old Approach
collectingAndThen
Modern Approach
stream.toList()
Since JDK
16
Difficulty
Intermediate
JDK Support
Unmodifiable collectors
Available
Widely available since JDK 16 (March 2021)
How it works
Java 10 added toUnmodifiableList(), toUnmodifiableSet(), and toUnmodifiableMap() to replace the verbose collectingAndThen wrapper. For lists specifically, Java 16's stream.toList() provides an even simpler alternative โ no collect() call at all. Use toUnmodifiableSet() and toUnmodifiableMap() for other collection types.
Related Documentation
Proof