Collectors minBy() and maxBy() method in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; // `Payroll` class having `employee` and `income` as private fields class Payroll { private String employee; private Integer income; public Payroll(String employee, Integer income) { this.employee = employee; this.income = income; } public Integer getIncome() { return income; } // other getters and setters @Override public String toString() { return "[" + employee + ", " + String.valueOf(income) + "]"; } public static Payroll max(Payroll x, Payroll y) { return x.getIncome() > y.getIncome() ? x : y; } } class Main { // Program to demonstrate `Collectors.minBy()` and `Collectors.maxBy()` // methods in Java 8 and above public static void main(String[] args) { Payroll p1 = new Payroll("Employee1", 115000); Payroll p2 = new Payroll("Employee2", 100000); Payroll p3 = new Payroll("Employee3", 120000); List<Payroll> salaries = Arrays.asList(p1, p2, p3); // get a person with the minimum income Payroll min = salaries.stream() .collect(Collectors.minBy( Comparator.comparingInt(Payroll::getIncome))) .get(); System.out.println("Employee with minimum Salary " + min); // get a person with the maximum income Payroll max = salaries.stream() .collect(Collectors.maxBy( Comparator.comparingInt(Payroll::getIncome))) .get(); System.out.println("Employee with maximum Salary " + max); } } |
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:
|
1 2 3 4 5 6 7 8 9 |
// get a person with the minimum income Payroll min = salaries.stream() .collect(Collectors.minBy((x, y) -> x.getIncome() - y.getIncome())) .get(); // get a person with the maximum income Payroll max = salaries.stream() .collect(Collectors.maxBy((x, y) -> x.getIncome() - y.getIncome())) .get(); |
That’s all about the Collectors class minBy() and maxBy() method in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)