Collections Intermediate

Collect directly to an unmodifiable list with stream.toList().

โœ• 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.
๐Ÿ“

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
Unmodifiable collectors
Available

Widely available since JDK 16 (March 2021)

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.