Java - Stream Reduce Operation

Introduction

The reduce operation combines all elements of a stream to produce a single value.

Computing the sum, maximum, average, count, etc. of elements of a stream of integers are examples of the reduce operation.

The reduce operation takes two parameters called a seed and an accumulator.

The accumulator is a function. If the stream is empty, the seed is the result.

Otherwise, seed and an element are passed to the accumulator, which returns another partial result.

This repeats until all elements are passed to the accumulator.

The last value returned from the accumulator is the result of the reduce operation.

Stream interfaces contain two methods called reduce() and collect() to perform generic reduce operations.

Methods such as sum(), max(), min(), count(), etc. are also available to perform specialized reduce operations.

Stream<T> interface reduce() method has three overloaded versions:

Optional<T> reduce(BinaryOperator<T> accumulator)

      <U> U reduce(U identity, 
                   BiFunction<U,? super T,U> accumulator, 
                   BinaryOperator<U> combiner)
 
          T reduce(T identity, BinaryOperator<T> accumulator)
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
                 .reduce(0, Integer::sum);
System.out.println(sum);

To compute the sum of the incomes of all people, map the stream of people to a stream of their incomes using the map operation.

double sum = Person.persons()
                   .stream()
                   .map(Person::getIncome)
                   .reduce(0.0, Double::sum);
System.out.println(sum);

Related Topics