Java 16 Stream.toList() and Stream Changes
Java 16, released in March 2021, brought two additions to java.util.stream.Stream: the terminal operation toList(), which collects into an unmodifiable list, and the intermediate operation mapMulti(), an alternative to flatMap(). In the same release, records (JEP 395) and pattern matching for instanceof became final, and both changed how stream code looks.
This page focuses on Stream.toList() as the headline change, shows how it compares with older collectors, and how Java 16 features combine in pipelines. The method references are toList() and mapMulti().
1. Java 16 Stream Methods
// java.util.stream.Stream<T> (Java 16)
default List<T> toList()
default <R> Stream<R> mapMulti(BiConsumer<? super T, ? super Consumer<R>> mapper)
// also Java 16: mapMultiToInt, mapMultiToLong, mapMultiToDouble
toList() is specified to return an unmodifiable list in encounter order; unlike Collectors.toUnmodifiableList(), it accepts null elements.
2. How the Java 16 Changes Work
toList() is a default method: it collects the elements into an array and wraps it in an unmodifiable list. The JDK's own stream implementation overrides it with an efficient version. Because it is a Stream method, it needs no import of Collectors and reads naturally at the end of a pipeline.
Records make the element types of pipelines short and immutable, and pattern matching for instanceof lets mapMulti() filter and cast in one step. Together, Java 16 made typical stream code noticeably more compact.
toList() is shorter and safer for read-only results, which is the most common case.3. Java Examples
Example 1: toList() in everyday code (Java 16+)
Return the names of overdue library loans as a read-only list.
import java.time.LocalDate;
import java.util.List;
public class OverdueLoans {
record Loan(String member, String book, LocalDate due) { }
public static void main(String[] args) {
LocalDate today = LocalDate.of(2026, 11, 25);
List<Loan> loans = List.of(
new Loan("Hema", "Clean Pipelines", LocalDate.of(2026, 11, 20)),
new Loan("Ivan", "River Tales", LocalDate.of(2026, 12, 2)),
new Loan("Jaya", "Data Craft", LocalDate.of(2026, 11, 24)));
List<String> overdue = loans.stream()
.filter(l -> l.due().isBefore(today))
.map(l -> l.member() + ": " + l.book())
.toList(); // Java 16
System.out.println(overdue);
System.out.println("Read-only: " + isReadOnly(overdue));
}
static boolean isReadOnly(List<String> list) {
try {
list.add("x");
return false;
} catch (UnsupportedOperationException e) {
return true;
}
}
}
[Hema: Clean Pipelines, Jaya: Data Craft] Read-only: true
How it works: A record keeps the data class to one line, and toList() ends the pipeline without Collectors. The result cannot be changed by the caller.
Example 2: Migrating from collect(Collectors.toList()) (Java 16+)
Compare the three ways of collecting a list and their behaviour with modification and nulls.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ListCollectorsCompared {
static String tryAdd(List<String> list) {
try {
list.add("new");
return "modifiable";
} catch (UnsupportedOperationException e) {
return "unmodifiable";
}
}
public static void main(String[] args) {
List<String> source = Arrays.asList("a", null, "c");
List<String> a = source.stream().collect(Collectors.toList());
List<String> b = source.stream().toList();
System.out.println("Collectors.toList(): " + tryAdd(a) + ", nulls ok");
System.out.println("Stream.toList(): " + tryAdd(b) + ", nulls ok");
try {
source.stream().collect(Collectors.toUnmodifiableList());
} catch (NullPointerException e) {
System.out.println("toUnmodifiableList(): rejects nulls");
}
}
}
Collectors.toList(): modifiable, nulls ok Stream.toList(): unmodifiable, nulls ok toUnmodifiableList(): rejects nulls
How it works: When migrating, replace collect(Collectors.toList()) with toList() only where the result is not modified later. (Collectors.toList() is modifiable in current JDKs, although the specification does not promise it.)
Example 3: Java 16 features together (Java 16+)
From a mixed list of shapes, compute the areas of circles only, using records, pattern matching, mapMulti() and toList().
import java.util.List;
public class Java16Together {
interface Shape { }
record Circle(double radius) implements Shape { }
record Square(double side) implements Shape { }
public static void main(String[] args) {
List<Shape> shapes = List.of(new Circle(1.0), new Square(2.0), new Circle(2.5));
List<String> circleAreas = shapes.stream()
.<Circle>mapMulti((shape, sink) -> {
if (shape instanceof Circle c) { // pattern matching (Java 16)
sink.accept(c);
}
})
.map(c -> String.format("%.2f", Math.PI * c.radius() * c.radius()))
.toList(); // Java 16
System.out.println("Circle areas: " + circleAreas);
}
}
Circle areas: [3.14, 19.63]
How it works: Records define the shapes, pattern matching for instanceof tests and casts, mapMulti() emits only circles with the right type, and toList() collects. All four are final in Java 16.
4. Real-World Use Cases
- Service return values:
toList()for read-only DTO lists. - Refactoring: shorten pipelines when upgrading from Java 11 to 17 or 21.
- Type-based filtering:
mapMulti()with pattern matching on event or message hierarchies.
5. Important Points
- Java 16 or later; most teams adopt it through the Java 17 LTS release.
- Unmodifiable result: code that adds to the list breaks after migration.
- Nulls allowed in
toList(), unlikeList.of()andtoUnmodifiableList(). - Primitive streams have no
toList(); callboxed()first. mapMulti()often needs a type witness such as.<Circle>mapMulti(...).
6. List Collection Options Compared
| Method | Since | Modifiable | Nulls |
|---|---|---|---|
collect(Collectors.toList()) | 8 | Not specified (yes today) | Allowed |
collect(Collectors.toUnmodifiableList()) | 10 | No | Rejected |
toList() | 16 | No | Allowed |
collect(Collectors.toCollection(ArrayList::new)) | 8 | Yes, guaranteed | Allowed |
7. Common Mistakes and Best Practices
Migrating code that modifies the result
List<Task> tasks = repo.findAll().stream().filter(Task::open).toList();
tasks.add(extraTask); // UnsupportedOperationException after migrating
Search for writes to the list before switching, or collect with toCollection(ArrayList::new).
Calling toList() on an IntStream
IntStream has no toList(). Use boxed().toList() or toArray().
Other mistakes to avoid
- Assuming
toList()rejects nulls. - Expecting a deeply immutable result: mutable elements can still change.
- Using it on a Java 11 baseline.
8. Summary
- Java 16 added
Stream.toList()andmapMulti(). toList()returns an unmodifiable list that accepts nulls.- Records and pattern matching, final in Java 16, make pipelines shorter.
- Check for list modifications before migrating from
Collectors.toList().
9. References
Frequently Asked Questions (FAQ)
Q1. What did Java 16 add to the Stream API?
Stream.toList(), which collects into an unmodifiable list, and mapMulti() with its primitive variants, an alternative to flatMap(). Records and pattern matching for instanceof also became final in Java 16.
Q2. Is Stream.toList() the same as collect(Collectors.toList())?
No. toList() guarantees an unmodifiable list. Collectors.toList() makes no promise about mutability, although current JDKs return a modifiable ArrayList.
Q3. Can Stream.toList() contain nulls?
Yes. Unlike Collectors.toUnmodifiableList() and List.of(), Stream.toList() accepts null elements.
Q4. Should I replace all collect(Collectors.toList()) calls with toList()?
Only where the result is not modified afterwards. Code that adds to or sorts the returned list will throw UnsupportedOperationException.
Q5. Which LTS release includes Stream.toList()?
Java 17, the first long-term support release after Java 16, and every later release, including 21 and 25.