CodeBlanks Logo Icon CodeBlanks

reduce

Learn accumulation with reduce.

Reducing a stream to one value: reduce

reduce combines all elements of a stream into a single result. The two-argument form takes an identity value and a BinaryOperator<T>; the result is always of type T.

Example: prices.stream().reduce(0.0, Double::sum). Here 0.0 is the starting value and Double::sum is the operator that adds two values. For an empty stream the result is the identity; this makes it safe to use, unlike the form that returns an Optional.

The three-argument reduce

The three-argument reduce form takes an identity, an accumulator and a combiner. You use it when the result type differs from the stream element, for example reducing a Stream<String> to an int count.

Example: words.stream().reduce(0, (sum, w) -> sum + w.length(), Integer::sum). Here 0 is the identity, the second argument is the accumulator that adds each string's length, and the third is the combiner that merges partial results in a parallel stream. This form is also safe for serial streams.

Practice Sum prices with reduce

Create a List<Double> of values 12.5, 25.0 and 5.0. Sum the stream with reduce(0.0, Double::sum) and print the result with System.out.println.

Starter code

Main.java
import java.util.List;

// Sum prices with reduce
// Start from the 0.0 identity
// Print the total

Sample solution

Main.java
import java.util.List;

public class SumPrices {
    public static void main(String[] args) {
        List<Double> prices = List.of(12.5, 25.0, 5.0);
        double sum = prices.stream().reduce(0.0, Double::sum);
        System.out.println(sum);
    }
}

Expected output

42.5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the reduce call

Question
double sum = prices.stream()
    .reduce(____, Double::sum);
Answer
double sum = prices.stream()
    .reduce(0.0, Double::sum);

Explanation: The identity for addition is 0.0.

2 Match the reduce overloads

Term Meaning
reduce(BinaryOperator) Returns Optional<T>
reduce(identity, op) Returns T
reduce(id, acc, comb) Returns a different type

3 Which reduce overload returns Optional<T>?

  • reduce(identity, BinaryOperator)
  • reduce(BinaryOperator) Correct answer
  • reduce(identity, acc, comb)
  • reduce(identity, mapper)

Explanation: The single-argument reduce(BinaryOperator) returns Optional<T>.

All lessons in Advanced