Java 16 added Stream.toList() - shorter than collect(Collectors.toList()), but the result is unmodifiable. Pick the one that matches what the caller may do with it.
var mutable = Stream.of("a", "b").collect(Collectors.toList());
mutable.add("c");
System.out.println("collect(toList()) is mutable: " + mutable);
var fixed = Stream.of("a", "b").toList();
try {
fixed.add("c");
} catch (UnsupportedOperationException e) {
System.out.println("stream.toList() is unmodifiable: " + fixed);
}
collect(toList()) is mutable: [a, b, c]
stream.toList() is unmodifiable: [a, b]
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