Java
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.
Exercise 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());.
Show example solution
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());
}
}
Test yourself
-
Complete the collect call
List<String> longs = names.stream().filter(s -> s.length() > 3).____(Collectors.toList());
Show answer
List<String> longs = names.stream().filter(s -> s.length() > 3).collect(Collectors.toList());
-
Match the Collectors methods
- Collectors.toList()
- Produces a List
- Collectors.toSet()
- Unique set
- Collectors.joining(", ")
- Joins text
- Collectors.counting()
- Counts elements
-
What is the List gathered by stream().toList()?
- Empty
- Mutable
- Synchronized
- Unmodifiable
Show answer
Unmodifiable — The .toList() shortcut returns an unmodifiable List.
Next lesson: Summary - Stream API basics