Why Java Stream.toList() Differs from Collectors.toList() and How to Use Them

This article explains the difference between Java's Stream.toList() introduced in Java 16, which returns an unmodifiable list, and the traditional Collectors.toList() used in Java 8 that produces a mutable list, and shows how to achieve immutability across versions.

Programmer DD
Programmer DD
Programmer DD
Why Java Stream.toList() Differs from Collectors.toList() and How to Use Them

In a previous post I showed how to debug Java Stream operations. A reader asked why the stream can call toList() directly without collect(). The answer is that Stream.toList() was introduced in Java 16 and returns an unmodifiable list.

For developers still on Java 8, the equivalent is to use collect(Collectors.toList()), which creates a mutable list.

public class StreamTest {

    @Test
    void test() {
        List<String> list = List.of("blog.didispace.com", "spring4all.com", "openwrite.cn", "www.didispace.com");

        List<String> result = list.stream()
                .filter(e -> e.contains("didispace.com"))
                .filter(e -> e.length() > 17)
                .toList();

        System.out.println(result);
    }
}

Java 8 equivalent:

List<String> result = list.stream()
    .filter(e -> e.contains("didispace.com"))
    .filter(e -> e.length() > 17)
    .collect(Collectors.toList());

Stream.toList() and Collectors.toList()

Although both produce a List, they differ: Stream.toList() returns an unmodifiable list, while collect(Collectors.toList()) returns a mutable list that can be modified.

Source of Stream.toList() (Java 16):

default List<T> toList() {
    return (List<T>) Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray())));
}

To obtain an unmodifiable list in earlier Java versions, use Collectors.toUnmodifiableList(), which is available since Java 10:

List<String> result = list.stream()
    .filter(e -> e.contains("didispace.com"))
    .filter(e -> e.length() > 17)
    .collect(Collectors.toUnmodifiableList());

Note that Collectors.toUnmodifiableList() is not available in Java 8; it requires at least Java 10.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaStreamJava 8CollectorsImmutable ListtoList
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.