Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Stream toList: Usage and Key Differences

Learn how Java's Stream.toList() works, how it differs from collect(Collectors.toList()), and when to use each approach.

~5 min readJava
#Java Streams#Java 16#Collectors#Immutable List
A Java stream pipeline feeding into an immutable list, symbolizing the Stream.toList() operation.

Java 16 introduced Stream.toList(), a terminal operation that collects stream elements into a List. Unlike the older collect(Collectors.toList()), it returns an unmodifiable list and does not allow null elements. This article explains what toList() actually does, how it compares with the collector-based approach, and when each one is the better choice.

What Stream.toList() Actually Returns

Stream.toList() is a terminal operation that accumulates the stream's elements into a new List instance. The returned list is unmodifiable, meaning any attempt to add, remove, or replace elements throws UnsupportedOperationException. The implementation is not specified; it could be a list backed by a fixed-size array, but you should not rely on any particular internal structure.

Another important characteristic is that toList() does not permit null elements. If the stream contains a null, the operation throws NullPointerException at the point of collection. This is a deliberate design choice to align with the behavior of other unmodifiable collections and to avoid ambiguity in later operations.

The method is more concise than the collector approach and does not create a Collector object. That difference is usually minor, but it can be useful when processing many small streams.

A Minimal Example of Stream.toList()

Here is a straightforward usage that filters and collects a stream of strings:

java
List<String> names = Stream.of("Alice", "Bob", "Carol") .filter(name -> name.startsWith("A")) .toList(); System.out.println(names); // [Alice]

The pipeline is identical to what you would write with collect(Collectors.toList()), but the terminal call is shorter. The result is an unmodifiable list, so the following line fails at runtime:

java
names.add("Dave"); // throws UnsupportedOperationException

If you need a mutable list, you must use collect(Collectors.toList()) or copy the result into a new ArrayList.

Stream.toList() vs. collect(Collectors.toList())

Both operations collect stream elements into a List, but they differ in several meaningful ways. The table below summarizes the key distinctions:

AspectStream.toList()collect(Collectors.toList())
MutabilityUnmodifiableMutable (typically ArrayList)
Null elementsThrows NullPointerExceptionAllows nulls
Return typeList (implementation unspecified)List (usually ArrayList)
Java versionJava 16+Since Java 8
Implementation overheadLower (no Collector instance)Slightly higher due to collector machinery
SerializabilityNot guaranteedDepends on the actual list implementation

These differences are not just theoretical. The unmodifiable nature of toList() can prevent accidental modification and makes the code's intent clearer. However, if you are working with code that expects a mutable list or relies on null elements, switching to toList() will break at runtime.

When to Use Stream.toList() Over Other Collectors

Choose Stream.toList() when you need a read-only snapshot of the stream's output and you know that null elements are not possible. It is particularly useful in functional pipelines where the result is passed to another component that should not modify it.

If you need to collect into a specific list implementation, such as a LinkedList or a CopyOnWriteArrayList, use collect(Collectors.toCollection(...)) instead. Similarly, if you need to accumulate into an existing list, use forEachOrdered or a custom collector; toList() always creates a new list and does not let you specify the implementation.

For scenarios where null elements are valid data, collect(Collectors.toList()) remains the safer choice. The same applies when you must return a mutable list to callers who may add or remove elements.

Performance and Memory Behavior of toList()

The exact representation of the returned list is unspecified. The implementation may use an exact-size array, which can avoid the slack capacity that an ArrayList often retains. However, whether toList() is faster than collect(Collectors.toList()) depends on the JVM and the stream source. For typical stream sizes, the difference is usually small. If performance matters, measure your own workload.

Because the returned list is unmodifiable, it is safe to pass to code that should only read it. The main benefit of toList() is simpler code and a clear read-only contract, not a guaranteed performance improvement.

Compatibility: Java Version and Module Considerations

Stream.toList() was added in Java 16. If your project targets an older Java version, you cannot use it without a polyfill or a library that provides a similar method. For Java 8 through 15, collect(Collectors.toList()) is the standard approach.

The java.base module includes both Stream and Collectors, so no additional module dependency is required. However, toList() is not a drop-in replacement for a custom collector that returns a list, because it does not accept a collector.

When upgrading an existing codebase, you can safely replace collect(Collectors.toList()) with toList() only if you have verified that the resulting list is never modified and that null elements are impossible. Otherwise, the change will introduce runtime failures.

Edge Cases: Null Elements and Unmodifiable Results

The most common pitfall with toList() is encountering a null element in the stream. The operation throws NullPointerException during collection, which can be surprising if your stream is built from a source that allows nulls. For example:

java
List<String> items = new ArrayList<>(); items.add("A"); items.add(null); items.stream().toList(); // throws NullPointerException

This behavior is intentional and documented. If you need to preserve nulls, use collect(Collectors.toList()) or filter them out beforehand.

Another edge case is the unmodifiable nature of the result. Even if you never modify the list yourself, passing it to a library that attempts to sort or add elements will cause an exception. This is often desirable, but you must communicate this contract to downstream consumers.

Parallel Streams and toList()

For a parallel stream, toList() must still combine partial results from multiple threads. The exact strategy is implementation-specific; it is not guaranteed to be faster than collect(Collectors.toList()). The returned list is unmodifiable, which makes it safe to expose to other threads without worrying about concurrent modification.

If you need a mutable list from a parallel stream, use collect(Collectors.toList()) or a thread-safe collector, but you then give up that safety guarantee.

For most applications, the choice between toList() and collect(Collectors.toList()) should be driven by mutability and null-handling requirements, not by performance. Use toList() when you want a concise, read-only result and are certain that nulls are absent.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.