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.

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:

Sources (0)
See inline citations in the answer above.