Java 16 · Topic 3 of 3
Stream.toList()
Definition​
Stream.toList() (Java 16) ends a stream with an unmodifiable list, so you no longer write collect(Collectors.toList()) for the common case.
Example code​
A shorter way to finish a stream
import java.util.List;
class Demo {
public static void main(String[] args) {
List<String> names = List.of("asha", "ravi", "meera").stream()
.map(String::toUpperCase)
.toList(); // Java 16
System.out.println(names);
try {
names.add("JO");
} catch (UnsupportedOperationException e) {
System.out.println("the list is unmodifiable");
}
}
}
// Output:
// [ASHA, RAVI, MEERA]
// the list is unmodifiable
Finished this page? Track your progress (saved only in your browser).