Course contentsShow
← Java
Lesson 1512 of 2,87033. Streams API: Terminal OperationsFree lesson

reduce vs collect: When to Use Which

Comparing reduce for immutable reduction with collect for mutable reduction, and choosing the right tool.

reduce vs collect: When to Use Which

You'll learn: When to use reduce for immutable reductions versus collect for building mutable containers efficiently.

The Core Difference

Both reduce and collect combine stream elements into a single result, but they differ fundamentally in how they build that result:

  • reduce creates a new immutable value at each step by combining the accumulator with the next element
  • collect uses a mutable container (like a List, Set, or StringBuilder) that gets modified in place

Think of it like building a tower: reduce rebuilds the entire tower from scratch each time you add a block, while collect keeps one tower and just adds blocks to it.

When to Use reduce

Use reduce when:

  • Your result is immutable (numbers, strings created via concatenation)
  • You're computing a single scalar value (sum, product, min, max)
  • The operation naturally fits a binary operator pattern
int sum = numbers.stream()
    .reduce(0, Integer::sum);  // Good: immutable integers

When to Use collect

Use collect when:

  • You're building a mutable collection (List, Set, Map)
  • You're accumulating into a container like StringBuilder
  • Performance matters with many elements
List<String> list = stream.collect(Collectors.toList());  // Good: mutable list

Why? Using reduce to build a List would create a new list at each step—extremely inefficient. Using collect modifies one container throughout, which is much faster.

The Performance Trap

Never use reduce to build collections:

// BAD: Creates new list at each step!
List<String> bad = stream.reduce(
    new ArrayList<>(),
    (list, item) -> { list.add(item); return list; },
    (list1, list2) -> { list1.addAll(list2); return list1; }
);

Key Takeaway: Use reduce for immutable reductions (numbers, simple values); use collect for mutable containers (List, Set, Map). When in doubt about collections, choose collect.