Java Comparable Comparator — Free Java Tutorial
Learn Java Comparable Comparator in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Java Comparable Comparator in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Java Comparable Comparator in Java
Comparable<T> (java.lang.Comparable) defines the natural ordering of a class. Implement its compareTo(T other) method. Collections.sort() and Arrays.sort() use this.
Comparator<T> (java.util.Comparator) defines an external, custom ordering. Pass it to sort methods as a second argument. Multiple Comparators can exist for one class.
compareTo() convention: return negative if this < other, 0 if equal, positive if this > other. Use Integer.compare(a, b) rather than a - b to avoid overflow.
Java 8+ Comparator.comparing() creates Comparators from key extractors. Chain with .thenComparing() for multi-level sorting. .reversed() inverts order.
Java Comparable Comparator — Syntax
class Student implements Comparable<Student> {
int marks;
@Override
public int compareTo(Student other) {
return Integer.compare(this.marks, other.marks);
}
}
Comparator<Student> byName = Comparator.comparing(s -> s.name);
Comparator<Student> byMarksDesc =
Comparator.com
Learn Java Comparable Comparator step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →