Find Maximum and Minimum of Custom Objects in Java

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


 

1. Stream.max()

The idea is to convert the list of objects into a Stream of objects and then use 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, for finding the minimum object in the stream, we can use Stream#min() function.

 

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. 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. Similary, 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. Stream.reduce()

We can also perform reduction operation on elements of the stream by using 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 reduce() method which performs a reduction on the elements of the stream, using the provided identity value and an associative accumulation function and returns the reduced value.

Download   Run Code

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz