What is the difference between count(), sum(), and reduce() in Java 8 Streams?

count(), sum(), and reduce() are all terminal Stream operations for aggregating elements, but they differ in generality: count() tallies elements, sum() (on primitive streams) totals numeric values, and reduce() is a general-purpose combiner for arbitrary accumulation logic.

Key Points: • count() returns a long representing the number of elements in the stream, regardless of their type. • sum() only exists on the primitive specializations IntStream, LongStream, and DoubleStream — a Stream<Integer> has no sum() method directly. • reduce() takes an identity value and a BinaryOperator (or just a BinaryOperator, returning an Optional) and can implement sums, products, max, concatenation, or any custom accumulation. • sum() is effectively a specialized, optimized case of what reduce() could also express, e.g. stream.reduce(0, Integer::sum). • Choosing between them is about intent: use count() for size, sum() for a quick primitive total, and reduce() when the aggregation logic doesn't fit a built-in method.

Example: For a Stream<Integer> of order amounts, mapToInt(Integer::intValue).sum() quickly totals them, while the same result could be produced more generally with reduce(0, Integer::sum), and stream.count() would instead just report how many orders there were.

Code Example:

List<Integer> amounts = Arrays.asList(120, 45, 300, 75);

long orderCount = amounts.stream().count();
int total = amounts.stream().mapToInt(Integer::intValue).sum();
int totalViaReduce = amounts.stream().reduce(0, Integer::sum);

Interview Tip: A concise interview answer is:

"count() gives me the number of elements, sum() is a convenience method on the primitive streams like IntStream for totaling numbers, and reduce() is the general-purpose tool that can implement sum, product, max, or any custom combining logic through an identity value and a BinaryOperator. In practice, sum() is really just a specialized reduce()."