Introduction
The Java Comparator interface is used to define custom sorting logic for objects. It is part of the Java Collections Framework and belongs to the java.util package. Unlike the Comparable interface, which defines a single natural ordering inside a class, Comparator allows you to create multiple sorting strategies without modifying the original class.
Comparator is especially useful when you need to sort objects in different ways. For example, an employee list can be sorted by employee ID, name, salary, or department using different Comparator implementations. This flexibility makes Comparator one of the most commonly used interfaces in Java applications.
The Comparator interface contains a single abstract method:
int compare(T o1, T o2);
The compare() method compares two objects and returns:
- A negative value if the first object should come before the second.
- Zero if both objects are considered equal.
- A positive value if the first object should come after the second.
Since Java 8, Comparator has become even more powerful by supporting lambda expressions, method references, and utility methods such as comparing(), thenComparing(), and reversed(). These features allow developers to write clean, concise, and readable sorting code.
What is Java Comparator?
A Comparator is an interface that allows objects to be sorted according to custom comparison logic.
It belongs to the java.util package.
Declaration:
public interface Comparator<T> {
int compare(T o1, T o2);
}
Unlike Comparable:
- Comparator compares two different objects.
- Multiple Comparator classes can exist for the same object.
- The original class does not need to be modified.
Why Do We Need Comparator?
Suppose you have an Employee class.
| ID | Name | Salary |
|---|---|---|
| 103 | Rahu | 50000 |
| 101 | Amit | 60000 |
| 102 | Neha | 5000 |
Sometimes you need to sort:
- By Employee ID
- By Name
- By Salary
A single Comparable implementation cannot efficiently handle all these requirements.
Comparator solves this problem by allowing multiple sorting strategies.
Syntax
Creating a Comparator
class NameComparator
implements Comparator<Employee>{
@Override
public int compare(Employee e1,
Employee e2){
return e1.name.compareTo(e2.name);
}
}
compare() Method
int compare(T o1, T o2)
Return values:
| Return Value | Meaning |
|---|---|
| Negative | First object comes before second |
| Zero | Both objects are equal |
| Positive | First object comes after second |
How Comparator Works
The sorting process is:
- Create a Comparator class.
- Implement the Comparator interface.
- Override the compare() method.
- Pass the Comparator object to Collections.sort() or List.sort().
Java automatically calls compare() while sorting.
Example 1: Sorting Strings
import java.util.*;
public class ComparatorExample {
public static void main(String[] args) {
List<String> names =
Arrays.asList("Rahul",
"Amit",
"Neha");
Collections.sort(names);
System.out.println(names);
}
}
Output
Strings already implement Comparable, but Comparator can also be supplied for custom ordering.
Example 2: Comparator with Custom Class
import java.util.*;
class Student{
int rollNo;
String name;
Student(int rollNo,String name){
this.rollNo = rollNo;
this.name = name;
}
}
class RollComparator
implements Comparator{
@Override
public int compare(Student s1,
Student s2){
return Integer.compare(s1.rollNo,
s2.rollNo);
}
}
public class Main{
public static void main(String[] args){
List list =
new ArrayList();
list.add(new Student(103,"Rahul"));
list.add(new Student(101,"Amit"));
list.add(new Student(102,"Neha"));
Collections.sort(list,
new RollComparator());
for(Student s:list){
System.out.println(s.rollNo
+" "+s.name);
}
}
}
Output
102 Neha
103 Rahul
Example 3: Sorting by Name
class NameComparator
implements Comparator<Student>{
@Override
public int compare(Student s1,
Student s2){
return s1.name.compareTo(s2.name);
}
}
Output
102 Neha
103 Rahul
Example 4: Sorting by Salary
class SalaryComparator
implements Comparator<Employee>{
@Override
public int compare(Employee e1,
Employee e2){
return Double.compare(e1.salary,
e2.salary);
}
}
Now employees are sorted according to salary instead of ID or name.
Example 5: Using Lambda Expression (Java 8+)
Collections.sort(list,
(s1, s2) ->
s1.name.compareTo(s2.name));
Or:
list.sort(
Comparator.comparing(
student -> student.name
)
);
This approach is shorter, cleaner, and preferred in modern Java applications.
Example 6: Sorting in Descending Order
list.sort(
Comparator.comparing(
Student::getRollNo
).reversed()
);
Output
102 Neha
101 Amit
Comparator Utility Methods (Java 8+)
Java 8 introduced several helper methods.
comparing()
Comparator.comparing(Student::getName)
Sorts by name.
reversed()
Comparator.comparing(Student::getName)
.reversed();
Sorts in reverse order.
thenComparing()
Comparator.comparing(Student::getDepartment)
.thenComparing(Student::getName);
Sorts by department first, then by name.
comparingInt()
Comparator.comparingInt(Student::getRollNo);
Efficiently compares integer values.
comparingDouble()
Comparator.comparingDouble(Employee::getSalary);
Compares double values.
Comparator vs Comparable
| Feature | Comparator | Comparable |
|---|---|---|
| Package | java.util | java.lang |
| Method | compare() | compareTo() |
| Number of Sorting Orders | Multiple | One |
| Original Class Modification | No | yes |
| Natural Ordering | No | Yes |
| Custom Ordering | Yes | Limited |
| Flexibility | High | Moderate |
Real-life Example
Imagine an E-commerce Application.
Products:
| ID | Name | Salary |
|---|---|---|
| 103 | Rahu | 50000 |
| 101 | Amit | 60000 |
| 102 | Neha | 5000 |
Possible sorting options:
- Price Low to High
- Price High to Low
- Product Name
- Product ID
Each sorting option can have its own Comparator.
Other real-world applications include:
- Student management systems
- Employee payroll systems
- Banking software
- Inventory management
- Hotel booking systems
- Hospital management
- Airline reservation systems
- Product catalogs
Advantages of Comparator
- Supports multiple sorting criteria
- Does not modify the original class
- Easy to reuse
- Cleaner design
- Supports lambda expressions
- Works well with Java Streams
- Easy to maintain
- Ideal for large enterprise applications
Limitations of Comparator
- Requires additional Comparator classes (unless using lambdas)
- Slightly more code than Comparable in simple cases
- Managing many Comparator implementations may increase complexity if not organized properly
Common Mistakes
1. Returning Arbitrary Numbers
Incorrect:
return 100;
Always compare actual fields.
Correct:
return Integer.compare(a.id,b.id);
2. Comparing Strings Using ==
Incorrect:
return s1.name==s2.name ? 0 : 1;
Correct:
return s1.name.compareTo(s2.name);
3. Using Subtraction for Large Numbers
Incorrect:
return e1.salary-e2.salary;
Better:
return Double.compare(e1.salary,
e2.salary);
This avoids overflow and precision issues.
4. Ignoring Null Values
If objects or fields can be null, use:
Comparator.nullsFirst(
Comparator.naturalOrder()
);
or
Comparator.nullsLast(
Comparator.naturalOrder()
);
5. Creating Unnecessary Comparator Classes
Instead of writing:
class NameComparator...
Modern Java allows:
list.sort(
Comparator.comparing(
Student::getName
)
);
This is more concise and easier to read.
Best Practices
- Use Integer.compare(), Long.compare(), and Double.compare() instead of subtraction.
- Prefer lambda expressions in Java 8 and later.
- Use Comparator.comparing() for cleaner code.
- Chain comparisons using thenComparing() for multi-level sorting.
- Keep comparison logic consistent and deterministic.
- Reuse Comparator instances when possible.
Time Complexity
The Comparator itself performs a single comparison in constant time for simple fields. Overall sorting depends on the sorting algorithm used.
| Operation | Time Complexity |
|---|---|
| Collections.sort() | O(1) |
| Arrays.sort() | O(n log n) |
| List.sort() | O(n log n) |
| Arrays.sort() | O(n log n) |
Conclusion
The Java Comparator interface is a powerful and flexible way to implement custom sorting in Java. Unlike Comparable, it allows multiple sorting strategies without modifying the original class, making it ideal for enterprise applications where objects need to be sorted in different ways.
With the introduction of Java 8, features such as lambda expressions, method references, and utility methods like comparing(), thenComparing(), and reversed() have made Comparator even easier to use. By understanding Comparator, its methods, best practices, and differences from Comparable, you can write cleaner, more maintainable Java code and confidently solve sorting-related problems in real-world projects and Java interviews.