Java can sort numbers and strings by itself, but it does not know how to sort your own objects. Should students be ordered by name, by CGPA, or by department and then CGPA? Java gives you two tools to answer that. Comparable lets a class define its one natural order. Comparator defines any number of other orders from outside the class. This lesson uses both, including the modern Comparator.comparing style.
In this lesson you will learn
- Implementing
ComparableandcompareTo - What negative, zero and positive results mean
- Building comparators with
Comparator.comparing - Reversing and chaining with
reversed()andthenComparing - When to use
Comparableand when to useComparator
You should know ArrayList and lambda expressions.
Comparable: the Natural Order
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
// Comparable: the class defines its own "natural" order
static class Student implements Comparable<Student> {
String name;
double cgpa;
Student(String name, double cgpa) { this.name = name; this.cgpa = cgpa; }
@Override
public int compareTo(Student other) {
return this.name.compareTo(other.name); // alphabetical by name
}
@Override
public String toString() { return name + "(" + cgpa + ")"; }
}
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(
new Student("Tania", 3.95), new Student("Arif", 3.41),
new Student("Nusrat", 3.82), new Student("Mitu", 3.67)));
Collections.sort(list); // uses compareTo
System.out.println(list);
Student a = list.get(0), n = list.get(2);
System.out.println("Arif vs Nusrat: " + a.compareTo(n));
System.out.println("Nusrat vs Arif: " + n.compareTo(a));
System.out.println("Arif vs Arif: " + a.compareTo(a));
}
}
Output
[Arif(3.41), Mitu(3.67), Nusrat(3.82), Tania(3.95)]
Arif vs Nusrat: -13
Nusrat vs Arif: 13
Arif vs Arif: 0
implements Comparable<Student>promises acompareTomethod.Collections.sort,TreeSetandTreeMapall use it.a.compareTo(b)returns a negative number ifacomes first, zero if they are equal in order, and a positive number ifacomes afterb. Only the sign matters, not the size: -13 just means “before”.- Here the natural order is alphabetical by name, so the list is sorted Arif, Mitu, Nusrat, Tania.
- Use
Comparablewhen there is one obvious order for the type, like numbers, dates or names.
Comparator: Any Order You Need
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
record Student(String name, String dept, double cgpa) {}
static String names(List<Student> list) {
return list.stream().map(Student::name).collect(Collectors.joining(" "));
}
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(
new Student("Tania", "CSE", 3.95), new Student("Arif", "EEE", 3.41),
new Student("Nusrat", "CSE", 3.82), new Student("Rafi", "EEE", 2.98),
new Student("Mitu", "CSE", 3.67)));
// Comparator: an order defined outside the class
list.sort(Comparator.comparingDouble(Student::cgpa).reversed());
System.out.println(names(list));
// Several keys: department, then CGPA high to low
list.sort(Comparator.comparing(Student::dept)
.thenComparing(Student::cgpa, Comparator.reverseOrder()));
System.out.println(list.stream().map(s -> s.dept() + ":" + s.name())
.collect(Collectors.joining(" ")));
// Old-style anonymous comparator, by name length then name
list.sort(new Comparator<Student>() {
@Override
public int compare(Student x, Student y) {
int byLength = Integer.compare(x.name().length(), y.name().length());
return byLength != 0 ? byLength : x.name().compareTo(y.name());
}
});
System.out.println(names(list));
System.out.println(list.stream().max(Comparator.comparingDouble(Student::cgpa)).get().name());
}
}
Output
Tania Nusrat Mitu Arif Rafi
CSE:Tania CSE:Nusrat CSE:Mitu EEE:Arif EEE:Rafi
Arif Mitu Rafi Tania Nusrat
Tania
Comparator.comparingDouble(Student::cgpa)builds a comparator from a key: “compare students by their CGPA”..reversed()turns it into highest first.thenComparingadds a tie-breaker. Students are grouped by department, and within each department sorted by CGPA from high to low.- The third sort shows the older style: an anonymous class with a
compare(x, y)method. It sorts by name length, then alphabetically. The lambda style above does the same job in less code. - Comparators work everywhere an order is needed:
list.sort,stream().max,TreeMapandPriorityQueue. Integer.compare(a, b)is the safe way to compare numbers insidecompare. The shortcuta - bcan overflow for large or negative values.
Comparable vs Comparator
| Comparable | Comparator | |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T other) | compare(T a, T b) |
| Where it lives | Inside the class being sorted | Outside, as a separate object or lambda |
| How many orders | One natural order | As many as you like |
| Used by | Collections.sort(list), TreeSet | list.sort(cmp), new TreeSet<>(cmp) |
Common Mistakes
- Returning
a - bfrom a comparison; it can overflow. UseInteger.compareorComparator.comparingInt. - Making
compareTodisagree withequals. ATreeSettreats elements that compare as 0 as duplicates and keeps only one. - Sorting a
List.of(...)list, which is unmodifiable and throws an exception. Copy it into anArrayListfirst. - Forgetting null values; use
Comparator.nullsFirstornullsLastwhen a key can be null.
Practice Exercises
Exercise 1. Sort the students by name length, shortest first, using Comparator.comparingInt.
Show answer
list.sort(Comparator.comparingInt(s -> s.name().length()));
The sort is stable, so students with names of equal length keep their previous relative order.
Exercise 2. Create a TreeSet of strings that ignores case, so “Dhaka” and “dhaka” count as the same city.
Show answer
TreeSet<String> cities = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
cities.add("Dhaka");
cities.add("dhaka");
cities.add("Sylhet");
System.out.println(cities); // [Dhaka, Sylhet]
Frequently Asked Questions
Is Java’s sort stable?
Yes for objects. List.sort and Collections.sort keep equal elements in their original order, which is what makes sorting by one key and then another work as expected.
Can a record implement Comparable?
Yes. A record can implement any interface: record Student(String name, double cgpa) implements Comparable<Student>, with a compareTo method in its body.
Summary
Comparablegives a class its natural order throughcompareTo.Comparatordefines extra orders outside the class.- Build comparators with
comparing,reversedandthenComparing. - Compare numbers with
Integer.compare, never subtraction.
