00:00

Java Stream collect() Method

Last updated:

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

Stream.java (API)
// 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.

Usage
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()).

How collect() builds a result collect uses a supplier to create an empty container, an accumulator to add each element to it, and, for parallel streams, a combiner to merge partial containers. A finisher can convert the container into the final result. Suppliernew container CREATE accumulatoradd element combinermerge parts finisheroptional result RList, Map, ... RESULT FILL AND MERGE
Figure 1: A collector describes four steps. Sequential streams use one container; parallel streams build several and merge them with the combiner.

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.

CollectBasics.java
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);
    }
}
Output
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.

SalesPerRegion.java
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);
    }
}
Output
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.

ThreeArgCollect.java
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);
    }
}
Output
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.

PassFailReport.java
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);
    }
}
Output
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 throws IllegalStateException.
  • Nulls: toMap() throws NullPointerException for null values; groupingBy() rejects null keys.
  • Mutability: Collectors.toList() gives no mutability guarantee; use toCollection(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; HashMap and HashSet results do not.

6. collect() vs reduce() and toList()

MethodKind of reductionResultBest for
collect(collector)Mutable (fills a container)Any containerLists, sets, maps, grouping, joining
toList()Mutable, fixedUnmodifiable ListSimple lists (Java 16)
reduce(identity, op)Immutable (combines values)A single valueSums, products, max of numbers
toArray()Fills an arrayAn arrayAPIs 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

Wrong
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:

ToMapMergeFix.java
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);
    }
}
Output
{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 Collectors method already exists.
  • Modifying the result of Collectors.toUnmodifiableList() or toList().

8. Summary

  • collect() performs a mutable reduction into a container.
  • Pass a Collector from Collectors, 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 use reduce() for single values.

9. References