What is the difference between Comparable and Comparator? Show how to sort students by CGPA (high to low) and then by name.
Show the explanation
Comparable<T>defines a class's natural order inside the class itself, throughcompareTo.Collections.sort(list),TreeSetandTreeMapuse it by default. There is only one natural order.Comparator<T>is a separate ordering object, so you can have as many orders as you like without touching the class.
record Student(String name, double cgpa) implements Comparable<Student> {
public int compareTo(Student o) { return name.compareTo(o.name); } // natural order: by name
}
List<Student> list = new ArrayList<>(List.of(
new Student("Ravi", 8.4), new Student("Asha", 9.1), new Student("Dev", 8.4)));
list.sort(Comparator.comparingDouble(Student::cgpa).reversed()
.thenComparing(Student::name));
// Asha 9.1, Dev 8.4, Ravi 8.4Avoid the old trick return a.score - b.score; — subtraction can overflow for large or negative values. Use Integer.compare(a, b) or the Comparator.comparing… helpers. Ideally compareTo should be consistent with equals, because sorted sets treat compareTo == 0 as "duplicate".
Original UniCircle question. Last reviewed 22 Oct 2026.
