Given a list of custom objects, find the maximum and minimum value of a field among custom objects using stream in Java.

1. Using Stream.max() method

The idea is to convert the list of objects into a stream of objects and then use the Stream#max() method that accepts a Comparator to compare objects based on a field value and returns an Optional containing the maximum object in the stream.

Similarly, we can use the Stream#min() method to find the minimum object in the stream.

Download  Run Code

Output:

User with minimum age: [Tom, 10]
User with maximum age: [George, 15]

 
We can also pass a lambda function as a comparator, as shown below:

Download  Run Code

2. Using Collectors

We can also use Collectors to find the maximum or minimum object in the list.

Collectors#maxBy() returns a Collector that produces the maximal object according to a given Comparator. Similarly, Collectors#maxBy() returns a Collector that produces the minimal object according to a given Comparator.

Download  Run Code

 
We can also pass a lambda function as a comparator, as shown below:

Download  Run Code

3. Using Stream.reduce() method

We can also perform a reduction operation on stream elements using the Stream.reduce() method that returns an Optional describing the reduced object.

Download  Run Code

 
Instead of creating a custom class for reduction operation and passing method reference, we can directly pass a lambda function, as shown below:

Download  Run Code

 
We can also use the overloaded version of the reduce() method, which performs a reduction on the stream elements, using the provided identity value and an associative accumulation method and returns the reduced value.

Download  Run Code

That’s all about finding the maximum and minimum of custom objects in Java.