Java 25 (LTS) reference · Stream API
Java Stream toList() Method
Collect a stream's elements into an unmodifiable List. Shorter than collect(Collectors.toList()).
Java 25 (LTS) Since Java 16
Syntax
stream.toList()
Return value
An unmodifiable List<T>.
Examples
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> squares = Stream.of(1, 2, 3).map(n -> n * n).toList();
System.out.println(squares);
}
}
Output
[1, 4, 9]
Run this on your computer — see “Get Started” for setup.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> fixed = Stream.of(3, 1).toList();
try {
fixed.add(2);
} catch (UnsupportedOperationException e) {
System.out.println("toList() is unmodifiable; use collect(Collectors.toCollection(ArrayList::new)) to edit");
}
}
}
Output
toList() is unmodifiable; use collect(Collectors.toCollection(ArrayList::new)) to edit
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 16 | Added |
Related
stream.collect(Collectors.joining())· Join a stream of strings into one string, with an optional separator, prefix and suffix.stream.collect(Collectors.groupingBy())· Group elements into a Map by a key function, optionally counting or summing each group.- Java Streams · tutorial