This post will discuss Collectors minBy() and maxBy() methods in Java.

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

We can use it 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

That’s all about the Collectors class minBy() and maxBy() method in Java.