Home » Reduce Java

Reduce Java

In Java, reducing is a terminal operation that aggregates a stream into a type or a primitive type. Java 8 provides Stream API contains set of predefined reduction operations such as average(), sum(), min(), max(), and count(). These operations return a value by combining the elements of a stream. In Java, reduce() is a method of the Stream interface. In this section, we will discuss the Java Stream.reduce() method in detail.

It is the method of combining all elements. For each element presented in the stream, the reduce() method applies the binary operator. In that stream, the first argument to the operator must return the value of the previous application and the second argument must return the current stream element.

It allows us to produce a single result from a sequence of elements by repeatedly applying a combining operation to the elements in the sequence called reducing.

There are the following three variants of Stream.reduce() methods:

1. reduce(BinaryOperator<T> accumulator)

It performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.

2. reduce(Tidentity, BinaryOperator<T> accumulator)

Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.

3. reduce(U identity, BiFunction<U,?super T,U> accumulator, BinaryOperator<U> combiner)

Performs a reduction on the elements of this stream, using the provided identity, accumulation, and combining functions.

In the above methods, three elements are used as parameter:

  • T: type of the data.
  • identity: It defines the initial value of reduction operation.
  • accumulator: It is a function to combine two values i.e. partial result of the reduction operation and the next element of the stream.
  • combiner: It combines the partial result of the reduction operation.

Let’s take some examples of operations to understand the reduce() method of the Stream class.

Java Stream.reduce() Example

ReduceExample1.java

Output:

Reduce Java

ReduceExample2.java

Output:

Reduce Java

ReduceExample3.java

Output:

Reduce Java

ReduceExample4.java

Output:

Reduce Java

ReduceExample5.java

Output:

Reduce Java


You may also like