In Java, the Comparator interface provides a way to compare two objects to determine their order. This is especially useful when you want to sort collections like lists or arrays in a custom order.
A custom Comparator is needed when the natural ordering of objects (as defined by their Comparable implementation) doesn’t meet your needs. For example, sorting a list of Employee objects by salary, name, or age may require different comparators.
Let’s walk through the process of creating a custom Comparator.
Consider a class Employee with fields name , age , and salary. We want to sort a list of Employee objects by salary in ascending order.
import java.util.Comparator; class Employee { private String name; private int age; private double salary; // Constructor, getters, and setters public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } public double getSalary() { return salary; } @Override public String toString() { return "Employee{" "name='" name ''' ", age=" age ", salary=" salary '}'; } } class SalaryComparator implements Comparator{ @Override public int compare(Employee e1, Employee e2) { return Double.compare(e1.getSalary(), e2.getSalary()); } }
In this example, the SalaryComparator class implements the Comparator interface and overrides the compare method to compare employees by their salary.
Now, let’s create a list of employees and sort it using our custom Comparator.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main { public static void main(String[] args) { Listemployees = new ArrayList(); employees.add(new Employee("John", 28, 50000)); employees.add(new Employee("Anna", 32, 75000)); employees.add(new Employee("Mike", 25, 45000)); System.out.println("Before Sorting:"); employees.forEach(System.out::println); // Sort employees by salary Collections.sort(employees, new SalaryComparator()); System.out.println(" After Sorting by Salary:"); employees.forEach(System.out::println); } }
Running the above code will produce the following output:
Before Sorting: Employee{name='John', age=28, salary=50000.0} Employee{name='Anna', age=32, salary=75000.0} Employee{name='Mike', age=25, salary=45000.0} After Sorting by Salary: Employee{name='Mike', age=25, salary=45000.0} Employee{name='John', age=28, salary=50000.0} Employee{name='Anna', age=32, salary=75000.0}
The list of employees is now sorted by their salary in ascending order, thanks to the custom Comparator.
Sometimes, you may need more complex comparison logic or want to sort by multiple fields.
Let’s modify our Comparator to first sort by salary and then by name in case of a tie.
class SalaryThenNameComparator implements Comparator{ @Override public int compare(Employee e1, Employee e2) { int salaryCompare = Double.compare(e1.getSalary(), e2.getSalary()); if (salaryCompare == 0) { return e1.getName().compareTo(e2.getName()); } return salaryCompare; } }
Using the SalaryThenNameComparator , you can now sort employees by salary and name:
Collections.sort(employees, new SalaryThenNameComparator());
Writing a custom Comparator function in Java allows you to tailor the sorting behavior of collections to meet specific needs. Whether you need a simple comparison by a single field or a complex sorting by multiple criteria, Comparator provides a flexible and powerful solution.
If you have any questions or need further clarification, feel free to leave a comment below!
Read posts more at : How to Write a Custom Comparator Function in Java?
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3