Java Stream collect() Method
collect() is a terminal operation of java.util.stream.Stream, available since Java 8, that performs a mutable reduction: it gathers the stream's elements into a container such as a List, Set, Map or StringBuilder. You either pass a ready-made Collector, usually from the Collectors class, or provide the container logic yourself with three functions.
This tutorial covers both overloads, the most important collectors, how collect() works in parallel, and how it differs from reduce() and toList().
1. Syntax and Method Signatures
// java.util.stream.Stream<T> (Java 8)
<R, A> R collect(Collector<? super T, A, R> collector)
<R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner)
In the first form, T is the element type, A the collector's internal accumulation type and R the result type. In the second form, the Supplier creates an empty container, the accumulator adds one element to a container, and the combiner merges two containers, which is needed for parallel streams.
Map<String, List<Order>> byCity = orders.stream()
.collect(Collectors.groupingBy(Order::city));
2. How collect() Works
For a sequential stream, collect() creates one container and calls the accumulator for every element. For a parallel stream, each worker builds its own container, and the combiner merges them. Because every thread has its own container, no locking is needed, which is why collect() is the safe way to build collections from parallel streams.
A Collector bundles these functions together with an optional finisher (for example, to make the result unmodifiable) and characteristics such as CONCURRENT or UNORDERED. The Collectors class provides dozens of ready-made collectors, and they can be nested, for example groupingBy(city, counting()).
3. Java Examples
Example 1: Collecting into common collection types (Java 16+)
From a list of course enrolments, build a list of names, a sorted set of courses and a map from student to course.
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class CollectBasics {
record Enrolment(String student, String course) { }
public static void main(String[] args) {
List<Enrolment> enrolments = List.of(
new Enrolment("Ria", "Java"), new Enrolment("Om", "SQL"),
new Enrolment("Ved", "Java"), new Enrolment("Tia", "Kafka"));
List<String> students = enrolments.stream()
.map(Enrolment::student)
.collect(Collectors.toList());
Set<String> courses = enrolments.stream()
.map(Enrolment::course)
.collect(Collectors.toCollection(TreeSet::new));
Map<String, String> studentToCourse = enrolments.stream()
.collect(Collectors.toMap(Enrolment::student, Enrolment::course, (a, b) -> a, TreeMap::new));
System.out.println("Students: " + students);
System.out.println("Courses: " + courses);
System.out.println("Map: " + studentToCourse);
}
}
Students: [Ria, Om, Ved, Tia]
Courses: [Java, Kafka, SQL]
Map: {Om=SQL, Ria=Java, Tia=Kafka, Ved=Java}
How it works: Each collector describes a different container: toList(), toCollection(TreeSet::new) for a sorted set without duplicates, and toMap() with a merge function and a TreeMap supplier.
Example 2: Grouping and summarising (Java 16+)
Total the sales per region and count the sales per region, using nested collectors.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class SalesPerRegion {
record Sale(String region, int amount) { }
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("East", 500), new Sale("West", 300), new Sale("East", 250),
new Sale("North", 900), new Sale("West", 120));
Map<String, Integer> totals = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new, Collectors.summingInt(Sale::amount)));
Map<String, Long> counts = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new, Collectors.counting()));
System.out.println("Totals: " + totals);
System.out.println("Counts: " + counts);
}
}
Totals: {East=750, North=900, West=420}
Counts: {East=2, North=1, West=2}
How it works: groupingBy() takes a downstream collector that decides what to do with each group. See groupingBy() for more.
Example 3: The three-function form (Java 9+)
Build a comma-separated list of SKUs with a StringBuilder, using supplier, accumulator and combiner directly.
import java.util.List;
public class ThreeArgCollect {
public static void main(String[] args) {
List<String> skus = List.of("A-10", "B-22", "C-31");
StringBuilder csv = skus.stream()
.collect(StringBuilder::new,
(sb, sku) -> sb.append(sb.length() == 0 ? "" : ",").append(sku),
(left, right) -> left.append(left.length() == 0 || right.length() == 0 ? "" : ",").append(right));
System.out.println(csv);
}
}
A-10,B-22,C-31
How it works: StringBuilder::new creates an empty container, the accumulator appends one SKU, and the combiner joins two partial builders when the stream runs in parallel. In practice, Collectors.joining(",") does this for you.
Example 4: Partitioning and joining in one report (Java 16+)
Split exam results into pass and fail lists, and produce a one-line summary.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class PassFailReport {
record Result(String student, int marks) { }
public static void main(String[] args) {
List<Result> results = List.of(
new Result("Anu", 78), new Result("Bob", 35), new Result("Cia", 91), new Result("Dan", 39));
Map<Boolean, List<String>> passFail = results.stream()
.collect(Collectors.partitioningBy(r -> r.marks() >= 40,
Collectors.mapping(Result::student, Collectors.toList())));
String summary = results.stream()
.map(r -> r.student() + ":" + r.marks())
.collect(Collectors.joining(", ", "[", "]"));
System.out.println("Passed: " + passFail.get(true));
System.out.println("Failed: " + passFail.get(false));
System.out.println("All: " + summary);
}
}
Passed: [Anu, Cia] Failed: [Bob, Dan] All: [Anu:78, Bob:35, Cia:91, Dan:39]
How it works: partitioningBy() always produces both keys, true and false. joining() takes a delimiter, prefix and suffix.
4. Real-World Use Cases
- Building API responses: collect DTOs into lists or maps keyed by id.
- Reports: group orders by month, region or status and sum or count them.
- Lookup tables: turn a list of products into a
Map<String, Product>by SKU. - Text output: join values into CSV lines or log messages.
5. Important Points
- Duplicate keys:
toMap()without a merge function throwsIllegalStateException. - Nulls:
toMap()throwsNullPointerExceptionfor null values;groupingBy()rejects null keys. - Mutability:
Collectors.toList()gives no mutability guarantee; usetoCollection(ArrayList::new)if you must modify the result. - Parallel safety:
collect()is safe for parallel streams because each thread has its own container. - Order: list collectors keep encounter order;
HashMapandHashSetresults do not.
6. collect() vs reduce() and toList()
| Method | Kind of reduction | Result | Best for |
|---|---|---|---|
collect(collector) | Mutable (fills a container) | Any container | Lists, sets, maps, grouping, joining |
toList() | Mutable, fixed | Unmodifiable List | Simple lists (Java 16) |
reduce(identity, op) | Immutable (combines values) | A single value | Sums, products, max of numbers |
toArray() | Fills an array | An array | APIs that need arrays |
Rule of thumb: use collect() when the result is a container, and reduce() when it is a single value.
7. Common Mistakes and Best Practices
Collecting into a map with duplicate keys
Map<String, Sale> byRegion = sales.stream()
.collect(Collectors.toMap(Sale::region, s -> s)); // IllegalStateException: Duplicate key East
Decide what should happen to duplicates. Group them, or provide a merge function:
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class ToMapMergeFix {
record Sale(String region, int amount) { }
public static void main(String[] args) {
List<Sale> sales = List.of(new Sale("East", 500), new Sale("West", 300), new Sale("East", 250));
Map<String, Integer> largestPerRegion = sales.stream()
.collect(Collectors.toMap(Sale::region, Sale::amount, Math::max, TreeMap::new));
System.out.println(largestPerRegion);
}
}
{East=500, West=300}
Other mistakes to avoid
- Adding to an outside list in
forEach()instead of collecting. - Writing a custom three-function collect when a
Collectorsmethod already exists. - Modifying the result of
Collectors.toUnmodifiableList()ortoList().
8. Summary
collect()performs a mutable reduction into a container.- Pass a
CollectorfromCollectors, or a supplier, accumulator and combiner. - It is safe for parallel streams because each thread fills its own container.
- Give
toMap()a merge function, and usereduce()for single values.
9. References
Frequently Asked Questions (FAQ)
Q1. What does collect() do in Java streams?
collect() is a terminal operation that performs a mutable reduction: it gathers the elements into a container such as a List, Set, Map or StringBuilder, described by a Collector or by supplier, accumulator and combiner functions.
Q2. What is the difference between collect() and reduce()?
collect() fills a mutable container and is the right choice for building collections. reduce() combines elements into a single value by repeatedly applying an operator and is best for sums, products and similar values.
Q3. Why does collect() need a combiner?
In a parallel stream each thread fills its own container. The combiner merges these partial containers into one result. For sequential streams it is not called, but it must still be correct.
Q4. Is collect(Collectors.toList()) the same as toList()?
Not exactly. Stream.toList(), added in Java 16, returns an unmodifiable list. Collectors.toList() makes no guarantee about the list type or mutability, although current JDKs return an ArrayList.
Q5. Is collect() safe with parallel streams?
Yes. Each thread accumulates into its own container and the containers are combined afterwards, so no shared mutable state is involved.