00:00

Java 16 Stream.toList() and Stream Changes

Last updated:

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

Stream.java (API)
// 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.

Collecting a list before and after Java 16 Left, Java 8 to 15: collect with Collectors.toList gives a list with no mutability guarantee; Collectors.toUnmodifiableList from Java 10 is read-only but rejects nulls. Right, Java 16 and later: stream.toList is short, read-only and accepts nulls. Java 8 - 15 .collect(Collectors.toList()) type and mutability unspecified toUnmodifiableList(): Java 10 read-only, but rejects nulls Java 16+ .toList() always unmodifiable keeps encounter order accepts null elements VS
Figure 1: 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.

OverdueLoans.java
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;
        }
    }
}
Output
[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.

ListCollectorsCompared.java
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");
        }
    }
}
Output
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().

Java16Together.java
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);
    }
}
Output
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(), unlike List.of() and toUnmodifiableList().
  • Primitive streams have no toList(); call boxed() first.
  • mapMulti() often needs a type witness such as .<Circle>mapMulti(...).

6. List Collection Options Compared

MethodSinceModifiableNulls
collect(Collectors.toList())8Not specified (yes today)Allowed
collect(Collectors.toUnmodifiableList())10NoRejected
toList()16NoAllowed
collect(Collectors.toCollection(ArrayList::new))8Yes, guaranteedAllowed

7. Common Mistakes and Best Practices

Migrating code that modifies the result

Breaks
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() and mapMulti().
  • 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