Java Streams learning path Level 2 This level ยท 3 of 13
Medium java streams

reduce versus collect

The 30 second answer

reduce is immutable reduction: you combine values into a new value, which fits sums and max. collect is mutable reduction into a container like a list or StringBuilder, so you avoid allocating a new object every step. Building a list with reduce is the classic anti-pattern โ€” use collect instead.

Could you say this in an interview?

reduce is immutable reduction: combines values into a new value (identity, accumulator, combiner), good for sums and max. collect is mutable reduction: accumulates into a mutable container (StringBuilder, ArrayList), avoiding the cost of creating new objects per step.

Requirements: accumulator associative, non-interfering, and stateless; identity must be a true identity for the combiner.

Anti-pattern: building a list with reduce (quadratic copying, or incorrect in parallel). [Opinion grounded in the package summary's reduction examples]

Sources (2)
  1. Reduction and mutable reductiondocs.oracle.com
  2. Stream.reduce / collectdocs.oracle.com
Previous
Next