When sorting custom objects (e.g. Student, Product, Employee), the JVM needs to know which attributes dictate ordering (e.g. sort by GPA, by Age, or by Name). Java provides two interfaces: Comparable and Comparator.
| Feature | Comparable<T> |
Comparator<T> |
|---|---|---|
| Package | java.lang (Imported automatically) |
java.util |
| Method to Implement | public int compareTo(T other) |
public int compare(T o1, T o2) |
| Sorting Scope | Single natural sorting order | Multiple sorting criteria |
| Modifies Class? | Yes (Original class must implement it) | No (Can be written as external lambda) |
Comparable: Natural Orderingpublic class Student implements Comparable<Student> {
int rollNo;
String name;
double gpa;
public Student(int rollNo, String name, double gpa) {
this.rollNo = rollNo;
this.name = name;
this.gpa = gpa;
}
// Natural ordering: Sorted ascending by rollNo
@Override
public int compareTo(Student other) {
return Integer.compare(this.rollNo, other.rollNo);
}
}
Comparator with Lambdas (Java 8+)import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ComparatorDemo {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(105, "Vikram", 3.4));
students.add(new Student(101, "Aarav", 3.9));
students.add(new Student(108, "Sneha", 3.7));
// Sort 1: Natural order via Comparable (rollNo)
Collections.sort(students);
// Sort 2: Custom sorting by Name using Lambda:
students.sort((s1, s2) -> s1.name.compareTo(s2.name));
// Sort 3: Modern Comparator chaining: Highest GPA first
students.sort(Comparator.comparingDouble((Student s) -> s.gpa).reversed());
}
}
Now let us explore the algorithms in the java.util.Collections utility class. Proceed to: Collections Utility Class →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Sorting lists with comparators.
Sorting elements via Comparator.
Sorting keys via Comparator.
Writing lambda comparator functions.