Collectors minBy() and maxBy() method in Java

In this post, we will discuss about Collectors minBy() and maxBy() methods in Java.


 

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

It can be used to find the maximum or minimum object in a Stream.

 

Download   Run Code

Output:

Employee with minimum Salary [Employee2, 100000]
Employee with maximum Salary [Employee3, 120000]

 
We can also pass a lambda function as a Comparator as shown below:

 

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