Java 8 Stream.reduce() method code examples

We can perform reduction operation on elements of the stream by using Stream.reduce() method that returns an Optional describing the reduced object or the the reduced value itself. In this post, we will see few simple example of 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 which takes two Person objects as input and returns the Person object with maximum age. Then we create a stream of Person objects via List.stream() method and pass 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 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 reduce() method which also takes an identity value along with associative accumulation function and performs a reduction on the elements of the stream.

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 Integers

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 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 reduce() method by passing the identity element.

 

Download   Run Code

 

 
Exercise:

1. Find minimum value of a field among custom objects.
2. Find minimum element from a List of Integers.

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

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of