STUDYECRAT Java : Comparable vs Comparator
60s
Java Comparable vs Comparator
Prove your skills in this interactive quiz
Live Code
Run snippets directly
Timed
60s per question
Scored
Earn 3D badges
★ Java Comparable vs Comparator: Key Interview Points
1. Implementing Natural Ordering with Comparable
class Product implements Comparable<Product> {
int id;
public int compareTo(Product p) {
return Integer.compare(this.id, p.id);
}
}
// Defines default sorting by product ID
int id;
public int compareTo(Product p) {
return Integer.compare(this.id, p.id);
}
}
// Defines default sorting by product ID
- Tip: Always implement consistent with equals() to avoid bugs in collections
- Real Use: Used in TreeSet/TreeMap for automatic sorting
2. Creating Multiple Sort Orders with Comparator
Comparator<Employee> bySalary = Comparator
.comparingInt(Employee::getSalary)
.thenComparing(Employee::getName);
List<Employee> employees = getEmployees();
employees.sort(bySalary);
// Sorts first by salary, then by name
.comparingInt(Employee::getSalary)
.thenComparing(Employee::getName);
List<Employee> employees = getEmployees();
employees.sort(bySalary);
// Sorts first by salary, then by name
- Tip: Use method references for better readability
- Real Use: Dynamic sorting in REST API responses
3. Null-Safe Comparison Techniques
List<String> list = Arrays.asList("A", null, "B");
list.sort(Comparator.nullsFirst(
Comparator.naturalOrder()
));
// nulls appear before other elements
list.sort(Comparator.nullsFirst(
Comparator.naturalOrder()
));
// nulls appear before other elements
- Tip: Use nullsLast() for databases-style sorting
- Real Use: Handling incomplete data in CSV processing
4. Implementing Reverse Order
List<Integer> nums = Arrays.asList(3,1,4);
nums.sort(Comparator.reverseOrder());
// Alternative:
nums.sort((a,b) -> b.compareTo(a));
// Both produce [4, 3, 1]
nums.sort(Comparator.reverseOrder());
// Alternative:
nums.sort((a,b) -> b.compareTo(a));
// Both produce [4, 3, 1]
- Tip: reverseOrder() is more readable than manual comparison
- Real Use: Displaying "newest first" in timelines
5. Multi-Field Custom Sorting
Comparator<Student> complexSort = Comparator
.comparing(Student::getGrade)
.thenComparing(s -> s.getAge(), Comparator.reverseOrder())
.thenComparing(Student::getName);
// Grade ASC → Age DESC → Name ASC
.comparing(Student::getGrade)
.thenComparing(s -> s.getAge(), Comparator.reverseOrder())
.thenComparing(Student::getName);
// Grade ASC → Age DESC → Name ASC
- Tip: Chain comparators using thenComparing()
- Real Use: School report card generation systems
💡 Pro Interview Tip
When asked about sorting, always mention both Comparable (natural order) and Comparator (custom order). Interviewers often test knowledge of both interfaces and their practical differences.