The Comparator interface in Java belongs to the java.util package and is used to define custom ordering for objects without modifying their class definition.
- Supports multiple sorting strategies for the same class, such as sorting students by name or age.
- Provides the compare() method as its single abstract functional method, allowing the use of lambda expressions.
import java.util.*;
class Student{
String name;
int age;
Student(String name, int age){
this.name = name;
this.age = age;
}
}
class Geeks{
public static void main(String[] args){
List<Student> students = new ArrayList<>();
students.add(new Student("Ajay", 27));
students.add(new Student("Sneha", 23));
students.add(new Student("Ajay", 21));
// Sort by name, then by age
Collections.sort(students, new Comparator<Student>(){
public int compare(Student s1, Student s2) {
int result = s1.name.compareTo(s2.name);
return result == 0 ? Integer.compare(s1.age, s2.age) : result;
}
});
for (Student s : students){
System.out.println(s.name + " : " + s.age);
}
}
}
Output
Ajay : 21 Ajay : 27 Sneha : 23
Explanation:
- StudentComparator implements Comparator<Student> and overrides the compare() method.
- Students are first compared by name in alphabetical order.
- When two students have the same name, Integer.compare() compares their ages in ascending order.
- Collections.sort() arranges the students according to the defined comparison logic.
Syntax of Comparator Interface
class MyComparator implements Comparator<Integer>{
@Override
public int compare(Integer obj1, Integer obj2) {
return Integer.compare(obj1, obj2);
}
}
The compare() method accepts two objects of the specified type and returns an integer representing their relative order.
compare() Return Values
- Negative value: The first object comes before the second object.
- Zero: Both objects are equal in sorting order.
- Positive value: The first object comes after the second object.
Note: Returning 0 indicates equality in sorting order, not necessarily equality according to the equals() method.
Using Comparator with Collections.sort()
The Collections.sort() method uses the supplied Comparator to determine the relative order of list elements.
Syntax:
public static <T> void sort(List<T> list, Comparator<? super T> c)
- list represents the list to be sorted.
- c represents the comparator that defines the sorting order.
The sorting algorithm calls the compare() method as needed to arrange the elements. The sort is stable, meaning elements that compare as equal retain their relative order.
Using Comparator with Lambda Expressions
Java 8 introduced lambda expressions and comparator helper methods, allowing custom sorting without creating a separate comparator class.
The sorting logic from the previous example can be simplified using:
students.sort(
Comparator.comparing((Student s) -> s.name)
.thenComparingInt(s -> s.age)
);
- comparing() defines the primary sorting criterion based on name.
- thenComparingInt() compares ages when names are equal.
- sort() arranges the list using the combined comparator.
Example: Program to sort students by age using a lambda expression.
import java.util.*;
class Student{
String name;
int age;
Student(String name, int age){
this.name = name;
this.age = age;
}
}
class Geeks{
public static void main(String[] args){
List<Student> students = new ArrayList<>();
students.add(new Student("Ajay", 27));
students.add(new Student("Sneha", 23));
students.add(new Student("Rahul", 21));
// Sort by age using a lambda expression
students.sort((s1, s2) -> Integer.compare(s1.age, s2.age));
for (Student s : students) {
System.out.println(s.name + " : " + s.age);
}
}
}
Output
Rahul : 21 Sneha : 23 Ajay : 27
Explanation:
- The lambda expression provides the implementation of compare().
- Integer.compare() compares the ages of two students.
- List.sort() arranges the students in ascending order of age.
Methods of Comparator Interface
Method | Description |
|---|---|
Compares two objects for ordering. | |
Checks whether another object is equal to this comparator. | |
Returns a comparator with reverse ordering. | |
Creates a comparator using an integer sort key. | |
comparing() | Creates a comparator using a specified sort key. |
thenComparing() | Adds a secondary comparison when the primary comparison returns zero. |
thenComparingInt() | Adds a secondary integer-based comparison. |
naturalOrder() | Returns a comparator that uses natural ordering. |
reverseOrder() | Returns a comparator that reverses natural ordering. |
nullsFirst() | Places null values before non-null values. |
nullsLast() | Places null values after non-null values. |