Streams: collectingAndThen finishes with a transformation

collectingAndThen applies a final function to a collector's result - the standard way to return an unmodifiable collection from a pipeline.

Code
var raw = List.of("b", "a", "c", "a");

List<String> sortedUnmodifiable = raw.stream().distinct().sorted()
        .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
System.out.println(sortedUnmodifiable);

try {
    sortedUnmodifiable.add("d");
} catch (UnsupportedOperationException e) {
    System.out.println("result is unmodifiable");
}
Output
[a, b, c]
result is unmodifiable
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30