Syntax
stream.collect(Collectors.methodName())Examples
Collecting to a List, Set, or Map
The most common collector operations.
import java.util.List;
import java.util.stream.Collectors;
List<String> names = List.of("John", "Zain", "Jamal", "John");
List<String> asList = names.stream().distinct().collect(Collectors.toList());
System.out.println(asList); // [John, Zain, Jamal]
var asMap = names.stream()
.distinct()
.collect(Collectors.toMap(name -> name, String::length));
System.out.println(asMap); // {John=4, Zain=4, Jamal=5}joining(): Building a String
Combining stream elements into a single delimited string.
import java.util.List;
import java.util.stream.Collectors;
List<String> names = List.of("John", "Zain", "Jamal");
String joined = names.stream().collect(Collectors.joining(", "));
System.out.println(joined); // John, Zain, Jamal
String withBrackets = names.stream().collect(Collectors.joining(", ", "[", "]"));
System.out.println(withBrackets); // [John, Zain, Jamal]groupingBy(): Grouping Elements
Splitting a stream into groups based on a classifier function, producing a Map.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
record Student(String name, String grade) {}
List<Student> students = List.of(
new Student("John", "A"),
new Student("Zain", "B"),
new Student("Jamal", "A"),
new Student("Amir", "C")
);
Map<String, List<Student>> byGrade = students.stream()
.collect(Collectors.groupingBy(Student::grade));
System.out.println(byGrade.get("A")); // [Student[name=John, grade=A], Student[name=Jamal, grade=A]]counting() and Downstream Collectors
Combining groupingBy() with a downstream collector like counting() for summary statistics.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
List<String> words = List.of("apple", "banana", "avocado", "blueberry", "cherry");
Map<Character, Long> countByFirstLetter = words.stream()
.collect(Collectors.groupingBy(w -> w.charAt(0), Collectors.counting()));
System.out.println(countByFirstLetter); // {a=2, b=2, c=1}Best practices
- Use Collectors.toList() (or the shorter .toList() method directly) as the default when you just need a plain result list
- Use Collectors.groupingBy() instead of manually building a Map<K, List<V>> with a loop - it handles the bucketing logic for you
- Combine groupingBy() with a downstream collector (counting(), summingInt(), etc.) to compute per-group statistics in one pass
- Use Collectors.joining() with a delimiter for building comma or newline-separated output instead of a manual StringBuilder loop
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification