Java · Easy · Free
Stream.toList() (Java 16) vs collect(Collectors.toList())?
JavaJava 8+FresherCollections
Stream.toList()
Java 16 adds stream.toList() returning an unmodifiable list—shorter than collect(Collectors.toList()) which returns mutable ArrayList.
toList()null-hostile like List.of elements.- Use
collect(toCollection(ArrayList::new))when mutation needed. - Immutable result safe to expose from service methods.
- Order preserved for ordered streams.
java
List<String> names = people.stream()
.map(Person::name)
.filter(n -> !n.isBlank())
.toList();Interview: explicitly say unmodifiable—difference from pre-16 collect habit.