The Comparator interface in Java is used to order objects of a user-defined class. It is not to be confused with the Comparable interface, which is implemented by the class to be sorted. A Comparator object is capable of comparing two objects of the same class. It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data member, for example, rollno, name, age, or anything else.
The Comparator interface contains two methods: compare(Object obj1, Object obj2) and equals(Object element). The compare() method compares obj1 with obj2 and returns an integer value based on whether obj1 is less than, equal to, or greater than obj2. The equals() method checks if the specified object is equal to the current object.
To use the Comparator interface, you need to implement it in a separate class. The class should have a compare() method that returns an integer value based on the comparison of two objects. You can then use this class to sort a collection of objects using the sort() method of the Collections class.
For example, suppose you have a class called "Item" and you want to sort a list of Item objects based on their ID. You can create a separate class called "ItemComparator" that implements the Comparator interface and overrides the compare() method to compare the IDs of two Item objects. You can then use the sort() method of the Collections class to sort the list of Item objects using the ItemComparator class.
Here is an example of how to use the Comparator interface to sort a list of Employee objects based on their last name:
import java.util.*;
public class EmployeeSort implements Comparator<Employee> {
@Override
public int compare(Employee valueA, Employee valueB) {
if (valueA.lastName.compareTo(valueB.lastName) != 0) {
// If lastNames are different, compare lastName
return valueA.lastName.compareTo(valueB.lastName);
} else {
// If lastNames are the same, compare firstName
return valueA.firstName.compareTo(valueB.firstName);
}
}
}
// To sort a list of Employee objects based on their last name:
List<Employee> employees = new ArrayList<>();
// Add Employee objects to the list
Collections.sort(employees, new EmployeeSort());