Introduction to reduction operations

Reduction stream operations are those operations that reduce the stream into a single value. The operations that we are going to discuss in this lesson are immutable operations because they reduce the result into a single-valued immutable variable. Given a collection of objects, we may need to get the sum of all the elements, the max element, or any other operation which gives us a single value as a result. This can be achieved through reduction operations.

Before we discuss all the reduction operations in detail, let’s first look at some key concepts of reduction:

  1. Identity – an element that is the initial value of the reduction operation and the default result if the stream is empty.

  2. Accumulator – a function that takes two parameters: a partial result of the reduction operation and the next element of the stream.

  3. Combiner – a function used to combine the partial result of the reduction operation when

    • the reduction is parallelized.

    • or there’s a mismatch between the types of the accumulator arguments and the types of the accumulator implementation.

Now, let’s look at some of the reduction methods.

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

As we can see, this method takes a binary operator as an input and returns an Optional that describes the reduced value.

The reduce() method iteratively applies the accumulator function on the current input element.

In the below example, we need to find the total salaries of all the employees in an organization.

For this, we are going to use the reduce(BinaryOperator<T> accumulator) operation.

Get hands-on with 1200+ tech skills courses.