CodeBlanks Logo Icon CodeBlanks

collect toList

Learn to collect into a list with collect(Collectors.toList()).

collect and Collectors

collect(Collectors.toList()) gathers stream elements into a new List. The result is a mutable List; the stream source is unaffected. Since Java 16 the .toList() shortcut exists; it returns an unmodifiable List.

Example: List<String> longs = names.stream().filter(s -> s.length() > 3).collect(Collectors.toList());. With Collectors.toSet() you get unique elements; Collectors.joining(", ") produces a single text.

The toList shortcut

The Java 16 .toList() shortcut is a shorter form of collect(Collectors.toList()). The result is an unmodifiable List; add or remove throws UnsupportedOperationException.

If a mutable list is needed, use collect(Collectors.toList()) or collect(Collectors.toCollection(ArrayList::new)). The shortcut is preferred when read-only access is enough; it is also more performant.

Practice Gather long names into a List

Declare List<String> names = new ArrayList<>();; add "Ayşe", "Alexander", "Alex". Gather names longer than five into a new List with List<String> longs = names.stream().filter(s -> s.length() > 5).collect(Collectors.toList());. Print the size of the result with System.out.println(longs.size());.

Starter code

Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // Declare List<String>, add 3 names, gather long ones with filter+collect, print size

    }
}

Sample solution

Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Ayşe");
        names.add("Alexander");
        names.add("Alex");
        List<String> longs = names.stream().filter(s -> s.length() > 5).collect(Collectors.toList());
        System.out.println(longs.size());
    }
}

Expected output

1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the collect call

Question
List<String> longs = names.stream().filter(s -> s.length() > 3).____(Collectors.toList());
Answer
List<String> longs = names.stream().filter(s -> s.length() > 3).collect(Collectors.toList());

Explanation: The collect terminal gathers the stream into a List.

2 Match the Collectors methods

Term Meaning
Collectors.toList() Produces a List
Collectors.toSet() Unique set
Collectors.joining(", ") Joins text
Collectors.counting() Counts elements

3 What is the List gathered by stream().toList()?

  • Empty
  • Mutable
  • Synchronized
  • Unmodifiable Correct answer

Explanation: The .toList() shortcut returns an unmodifiable List.

All lessons in Intermediate