stream.collect() / toList()
A terminal operation on streams that collects stream elements into a collection (Java 8+). You can pass a method from the Collectors class to collect() to convert the stream into a list, set, or map. Since Java 16, you can call toList() directly on a stream.
Syntax
// Collects the stream into a list. stream.collect(Collectors.toList()); // Collects the stream into a set. stream.collect(Collectors.toSet()); // Collects the stream into a map. stream.collect(Collectors.toMap(keyMapper, valueMapper)); // Collects the stream into an unmodifiable list (Java 16+). stream.toList();
Method List
| Method | Description |
|---|---|
| collect(Collector) | A terminal operation that collects stream elements into a collection of the specified type. |
| Collectors.toList() | Collects stream elements into an ArrayList (mutable). |
| Collectors.toSet() | Collects stream elements into a HashSet (duplicates are removed). |
| Collectors.toMap(k, v) | Collects stream elements into a HashMap using the specified key and value mapper functions. |
| toList() | Collects the stream into an unmodifiable list (Java 16+). Equivalent to collect(Collectors.toUnmodifiableList()). |
Sample Code
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
List<String> fruits = Arrays.asList("apple", "banana", "cherry", "avocado");
// Collects elements starting with 'a' into a list.
List<String> aFruits = fruits.stream()
.filter(f -> f.startsWith("a"))
.collect(Collectors.toList());
System.out.println(aFruits); // Prints [apple, avocado].
// Collects all elements into a set (duplicates are removed).
List<Integer> nums = Arrays.asList(1, 2, 2, 3, 3, 3);
Set<Integer> uniqueNums = nums.stream()
.collect(Collectors.toSet());
System.out.println(uniqueNums.size()); // Prints 3.
// Collects into a map with the string as the key and its length as the value.
Map<String, Integer> lengthMap = fruits.stream()
.collect(Collectors.toMap(f -> f, String::length));
System.out.println(lengthMap.get("apple")); // Prints 5.
// Uses toList() from Java 16+ (unmodifiable list).
List<String> upperList = fruits.stream()
.map(String::toUpperCase)
.toList(); // Java 16+
System.out.println(upperList); // Prints [APPLE, BANANA, CHERRY, AVOCADO].
Overview
collect() is the most versatile terminal operation on streams. By combining it with the collectors provided by the Collectors class, you can convert a stream into many different formats.
toList() introduced in Java 16 offers a concise syntax, but the returned list is unmodifiable — calling methods like add() will throw an UnsupportedOperationException. Use Collectors.toList() when you need a mutable list.
For creating streams, filtering, and mapping, see stream() / filter() / map().
If you find any errors or copyright issues, please contact us.