What is Comparator Interface in Java with Examples?
The Comparator interface contains compare() and equals() methods. The first method is utilized to compute two objects by returning an integer value. The other method is utilized for computing two comparator objects for equality.
Here are different examples of how to use the Comparator interface in Java:
Example 1: Sort a List based on the Length
In this example, a list of strings is considered and sort them based on their length instead of alphabetical order:
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("John");
list.add("Bob");
list.add("Alice");
Collections.sort(list);
System.out.println(list);
Collections.sort(list, new StringLengthComparator());
System.out.println(list);
}
} // A class is defined
class StringLengthComparator implements Comparator<String> {
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
}
The description of the above code is given below:
- First, create a custom Comparator class called StringLengthComparator that implements the Comparator<String> interface.
- It overrides the compare() method for comparing the length of two strings.
- In the end, pass an instance to the.sort() method for sorting the list using our custom comparator.
Output
The first output is the result of sorting the list using natural ordering, while the second output is the result of sorting the list using our custom comparator based on the length of each string.
Example 2: Sorting Objects Based on a Specific Field
Another example is conducted to sort objects based on a specific field. The Comparator interface is utilized to achieve this:
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>(); // Assign name, age and salaries
persons.add(new Person("Alice", 25, 50000));
persons.add(new Person("Bob", 30, 75000));
persons.add(new Person("Charlie", 20, 40000));
Comparator<Person> salaryComparator = new Comparator<Person>() {
// Sort persons based on salary
public int compare(Person p1, Person p2) {
return Integer.compare(p2.getSalary(), p1.getSalary());
}
};
Collections.sort(persons, salaryComparator); return sort values
// Print a sorted list of persons
for (Person person : persons) {
System.out.println(person);
}
}
}
class Person { // Define name, age, and salary
private String name; // scope within in a class
private int age;
private int salary;
public Person(String name, int age, int salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getSalary() {
return salary;
}
public String toString() {
return name + " (age " + age + ", salary $" + salary + ")";
}
}
The description of the code is given below:
- A class called “Person” with three fields: “name”, “age”, and “salary” is considered.
- After that, sort a collection of Person objects depending on their salary in descending order.
Output
The output shows that salaries have been sorted according to descending order.
Conclusion
In Java, the Comparator interface is a powerful tool that allows users to sort objects based on custom criteria. It overrides the compare() method, users can define their own comparison function and use it to sort collections of objects in a variety of ways. This article has explained the Comparator interface along with practical examples in Java.