How do I use Stream.toList() instead of collect(Collectors.toList())?

In Java 16, a convenient method Stream.toList() was introduced to simplify collecting elements of a Stream into a List. It provides a more concise alternative to collect(Collectors.toList()), which was used in older versions of Java.

Key Differences

  • Stream.toList() produces an immutable list, whereas collect(Collectors.toList()) produces a mutable list.
  • Stream.toList() guarantees immutability, meaning the resulting list cannot be structurally modified (additions, deletions, updates).
  • collect(Collectors.toList()) does not enforce immutability. It typically returns an ArrayList.

How to Replace collect(Collectors.toList()) with Stream.toList()

If you want to update your code to use Stream.toList() (introduced in Java 16), here’s how you can do it.

Using collect(Collectors.toList()) (Old Style):

package org.kodejava.util.stream;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        List<String> result = Stream.of("a", "b", "c")
                                    .collect(Collectors.toList());
        System.out.println(result);
    }
}

Using Stream.toList() (New Style):

package org.kodejava.util.stream;

import java.util.List;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        List<String> result = Stream.of("a", "b", "c")
                                    .toList(); // Simpler, concise, and immutable
        System.out.println(result);
    }
}

How to Modify Your Code:

  1. Replace .collect(Collectors.toList()) with .toList().
  2. Ensure your code works well with an immutable list because Stream.toList() returns a list that does not allow structural modifications.

Example Comparison:

Immutable List with Stream.toList():

List<String> result = Stream.of("a", "b", "c").toList();
result.add("d"); // Throws UnsupportedOperationException

Mutable List with collect(Collectors.toList()):

List<String> result = Stream.of("a", "b", "c").collect(Collectors.toList());
result.add("d"); // Works fine

Compatibility Note

  • If you are using Java 16 or above, prefer Stream.toList() for conciseness and immutability.
  • If you need a mutable list (e.g., you want to add or remove elements later), stick to collect(Collectors.toList()).

When to Use Each

  • Use Stream.toList() when immutability is preferred or sufficient.
  • Use collect(Collectors.toList()) when you need a list you can modify after creation.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.