collect and the Basic Collectors
Pour a stream into a List, Set, Map or String using collect and Collectors.
Open this lesson in the learning hubKey points
collectis the general terminal op: it pours the stream into a container you pick.Stream.toList()(Java 16+) is the short path, but the list it hands back is unmodifiable.- Need a mutable result? Use
Collectors.toCollection(ArrayList::new). Collectors.joining(sep, prefix, suffix)builds strings without a StringBuilder.Collectors.toMapthrows on duplicate keys. Pass a merge function unless the keys are truly unique.
Example
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<String> langs = List.of("Java", "Kotlin", "Scala", "Java");
List<String> immutable = langs.stream().distinct().toList();
List<String> mutable = langs.stream().collect(Collectors.toCollection(ArrayList::new));
Set<String> unique = langs.stream().collect(Collectors.toSet());
String csv = langs.stream().distinct().collect(Collectors.joining(", ", "[", "]"));
Map<String, Integer> lengths = langs.stream().distinct()
.collect(Collectors.toMap(s -> s, String::length));
System.out.println("immutable : " + immutable);
System.out.println("mutable : " + mutable);
System.out.println("set size : " + unique.size());
System.out.println("joined : " + csv);
System.out.println("toMap : " + new TreeMap<>(lengths));
// Duplicate keys throw unless you supply a merge function.
Map<Integer, String> byLength = langs.stream()
.collect(Collectors.toMap(String::length, s -> s, (a, b) -> a + "|" + b));
System.out.println("merged : " + new TreeMap<>(byLength));
try {
immutable.add("Groovy");
} catch (UnsupportedOperationException e) {
System.out.println("toList() result is unmodifiable");
}
}
}
toList() for a quick read-only list; collect() when you need control over the container.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Streams course, and every lesson in it is listed on the Streams contents page.