What is the difference between Comparable and Comparator in Java?
| Point | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T other) | compare(T a, T b) |
| Where | Inside the class | A separate object or lambda |
| Orders | One natural order | Many orders |
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Student(String name, int marks) implements Comparable<Student> {
@Override
public int compareTo(Student other) {
return this.name.compareTo(other.name); // natural order: by name
}
}
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(new Student("Meera", 95), new Student("Aman", 72), new Student("Riya", 88)));
java.util.Collections.sort(list); // uses compareTo
System.out.println(list);
list.sort(Comparator.comparingInt(Student::marks).reversed()); // another order
System.out.println(list);
}
}
Output
[Student[name=Aman, marks=72], Student[name=Meera, marks=95], Student[name=Riya, marks=88]]
[Student[name=Meera, marks=95], Student[name=Riya, marks=88], Student[name=Aman, marks=72]]
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |