We can perform a reduction operation on elements of a Java Stream using the Stream.reduce() method that returns an Optional describing the reduced object or the reduced value itself. This post will discuss a few simple examples of the Stream.reduce() method.

1. Find maximum value of a field among custom objects

Suppose we have a Person class with name and age as its fields. We also have a list of Person objects, and the goal is to find the person having maximum age.

The idea is to create a custom method that takes two Person objects as input and returns the Person object with the maximum age. Then we create a stream of Person objects via the List.stream() method and pass the reference of the custom method to the reduce() method for the reduction operation.

Download  Run Code

Output:

Person with maximum age is [George, 15]

 
We can also directly pass a lambda function instead of using a custom method, as shown below. It takes two parameters – a partial result of the reduction (in this example, an object with the maximum age of all processed objects so far) and the next element of the stream (in this example, a Person object). It returns a new value every time it processes an element of a stream.

Download  Run Code

 
There is another overloaded version of the reduce() method, which also takes an identity value along with the associative accumulation method and performs a reduction on the stream elements.

The identity element is both the initial value of the reduction and the default result if there are no elements in the stream.

Download  Run Code

2. Find maximum element from a list of Integer

Suppose we have a list of Integer, and the goal is to find the maximum element in the list.

The idea is to create a stream of Integer and pass the method reference of Integer.max() to the reduce() method for the reduction operation, which then returns an Optional describing the maximum value.

Download  Run Code

 
Here’s how we can use the overloaded version of the reduce() method by passing the identity element.

Download  Run Code

That’s all about the Stream.reduce() method in Java with code examples.

 
Exercise:

1. Find the minimum value of a field among custom objects.
2. Find the minimum element from a list of Integer.

 
Reference: Reduction (The Java™ Tutorials > Collections > Aggregate Operations)