Sorting numbers and strings in Java is easy. Collections.sort() puts [50, 10, 30] in order, and it sorts names alphabetically. But what happens when we try to sort a list of our own Student objects? Should Java sort them by name? By marks? By roll number? Java has no way of knowing.
We have to tell Java how to compare two objects. Java gives us two interfaces for this:
Comparable → the object knows how to compare itself (its "natural order")
Comparator → a separate object that compares two other objects (a "custom order")Understanding the difference between these two is a very common interview question.
The Comparison Rule
Both interfaces follow the same simple rule. A comparison method returns an int:
Return value | Meaning |
|---|---|
Negative number | The first object comes before the second |
Zero | Both are equal in ordering |
Positive number | The first object comes after the second |
Only the sign matters, not the exact number. For example, String already follows this rule:
System.out.println("apple".compareTo("banana"));
System.out.println("banana".compareTo("apple"));
System.out.println("apple".compareTo("apple"));Output:
-1
1
0Here we got -1 because 'a' and 'b' differ by one, but for other strings you could get -5 or 12. Never check for exactly -1 or 1. Check < 0, == 0, or > 0.
Comparable: Natural Ordering
The Comparable<T> interface (in java.lang, so no import needed) has one method:
int compareTo(T other);A class implements it to define its natural order, the "default" way its objects should be sorted. String, Integer, Double, and Character all implement Comparable, and that is exactly why Collections.sort() already works for them.
Let's give Student a natural order by marks:
import java.util.ArrayList;
import java.util.Collections;
class Student implements Comparable<Student> {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.marks, other.marks);
}
@Override
public String toString() {
return name + "(" + marks + ")";
}
}
class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("John", 85));
students.add(new Student("Alex", 72));
students.add(new Student("Jason", 91));
students.add(new Student("Priya", 72));
Collections.sort(students);
System.out.println(students);
}
}Output:
[Alex(72), Priya(72), John(85), Jason(91)]Integer.compare(x, y) returns a negative number, zero, or a positive number exactly as the rule requires. Notice that Alex and Priya both have 72 and stayed in their original order. Java's object sorting is stable: equal elements keep their relative order.
If a class does not implement Comparable and you call Collections.sort() on it, the code does not even compile. If you add such objects to a TreeSet or use them as TreeMap keys without a comparator, you get a ClassCastException at runtime, because those collections need to compare elements to keep them sorted.
Comparator: Custom Ordering
A class can have only one compareTo() method, so only one natural order. But in real applications we often need several orders: by marks for a rank list, by name for an attendance sheet, and so on. Also, sometimes we cannot change the class at all (for example, a class from a library).
That is where Comparator<T> (in java.util) helps. It is a separate object with one method:
int compare(T a, T b);Here is a complete example with two comparators:
import java.util.ArrayList;
import java.util.Comparator;
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
@Override
public String toString() {
return name + "(" + marks + ")";
}
}
class NameComparator implements Comparator<Student> {
@Override
public int compare(Student a, Student b) {
return a.name.compareTo(b.name);
}
}
class MarksComparator implements Comparator<Student> {
@Override
public int compare(Student a, Student b) {
return Integer.compare(a.marks, b.marks);
}
}
class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Priya", 72));
students.add(new Student("John", 85));
students.add(new Student("Jason", 91));
students.add(new Student("Alex", 72));
students.sort(new MarksComparator().reversed());
System.out.println("Highest first: " + students);
Comparator<Student> byMarksDescThenName =
new MarksComparator().reversed().thenComparing(new NameComparator());
students.sort(byMarksDescThenName);
System.out.println("Ties broken by name: " + students);
students.sort(new NameComparator());
System.out.println("By name: " + students);
}
}Output:
Highest first: [Jason(91), John(85), Priya(72), Alex(72)]
Ties broken by name: [Jason(91), John(85), Alex(72), Priya(72)]
By name: [Alex(72), Jason(91), John(85), Priya(72)]A few useful things are happening here:
list.sort(comparator)sorts a list using a comparator.Collections.sort(list, comparator)does the same thing.reversed()gives a new comparator with the opposite order.thenComparing(other)is used only when the first comparator says two objects are equal. Priya and Alex both have 72 marks, so they are then ordered by name.
Be careful with where you put reversed(). marks.reversed().thenComparing(name) means "marks high to low, then names A to Z". But marks.thenComparing(name).reversed() reverses both, so names become Z to A.
Using an Anonymous Class
Creating a whole named class for a comparator you use only once is a bit heavy. An anonymous class lets you write it on the spot:
students.sort(new Comparator<Student>() {
@Override
public int compare(Student a, Student b) {
return Integer.compare(a.name.length(), b.name.length());
}
});This sorts students by the length of their names.
Since Comparator has only one abstract method, it is a functional interface. In the upcoming chapters on functional interfaces and lambda expressions, you will see that the same comparator can be written in one short line:
students.sort((a, b) -> Integer.compare(a.name.length(), b.name.length()));For now, just remember that both forms mean exactly the same thing.
Ready-Made Comparators
Java already provides some comparators so you don't have to write them:
List<String> words = new ArrayList<>(List.of("banana", "Apple", "cherry", "apple"));
Collections.sort(words); // natural order
System.out.println(words);
words.sort(Collections.reverseOrder()); // reverse natural order
System.out.println(words);
List<Integer> nums = new ArrayList<>(List.of(40, 10, 30, 20));
nums.sort(Comparator.reverseOrder()); // same idea
System.out.println(nums);Output:
[Apple, apple, banana, cherry]
[cherry, banana, apple, Apple]
[40, 30, 20, 10]Notice that "Apple" comes before "apple". String comparison uses character codes, and all uppercase letters come before lowercase letters. If you want to ignore case, use String.CASE_INSENSITIVE_ORDER as the comparator.
Comparators also work with the sorted collections you met in the PriorityQueue and TreeSet/TreeMap chapters:
TreeSet<Integer> set = new TreeSet<>(Comparator.reverseOrder());
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());The second line is the standard way to turn Java's min-heap PriorityQueue into a max-heap, a trick used in many coding problems.
Comparable vs Comparator
Feature |
|
|
|---|---|---|
Package |
|
|
Method |
|
|
Where it is written | Inside the class being sorted | In a separate class or object |
Number of orders | One natural order | As many as you like |
Changes the class? | Yes | No |
Used by |
|
|
A simple way to decide: if there is one obvious "default" order for the class (like dates in time order), use Comparable. For every other order, use a Comparator.
Common Mistakes
1. Comparing by subtraction. You may see code like return a.marks - b.marks;. It works for small numbers but can overflow for large ones:
int a = Integer.MIN_VALUE, b = 1;
System.out.println(a - b); // should be negative!
System.out.println(Integer.compare(a, b));Output:
2147483647
-1a is clearly smaller than b, but a - b overflowed into a large positive number, which would sort the elements in the wrong order. Always use Integer.compare(), Long.compare(), or Double.compare().
2. A comparator that treats different objects as equal inside a TreeSet. A TreeSet uses the comparator (not equals()) to decide duplicates. If two different students have the same marks and the comparator only looks at marks, the second one is silently dropped:
TreeSet<Student> set = new TreeSet<>(new MarksComparator());
set.add(new Student("John", 85));
set.add(new Student("Alex", 72));
set.add(new Student("Priya", 72)); // compare() returns 0 → treated as duplicate
System.out.println(set);Output:
[Alex(72), John(85)]Priya disappeared. The fix is to add a tie-breaker with thenComparing() so that only truly identical students compare as 0.
3. Inconsistent comparisons. Your comparison must be consistent: if A comes before B, then B must come after A, and if A is before B and B is before C, then A must be before C. Breaking these rules can lead to strange orderings or even an IllegalArgumentException ("Comparison method violates its general contract!") during sorting.
4. Not handling null. Calling compareTo() on a null reference throws NullPointerException. If your list may contain null values, remove them first or use Comparator.nullsFirst() / Comparator.nullsLast().
Time Complexity of Sorting
Collections.sort() and list.sort() use an algorithm called TimSort (a mix of merge sort and insertion sort):
Time: O(n log n) comparisons in the worst case
O(n) when the list is already sorted
Stable: yes, equal elements keep their orderFor arrays of objects, Arrays.sort(array, comparator) uses the same algorithm. For arrays of primitives like int[], Arrays.sort() uses a different algorithm (Dual-Pivot Quicksort), and you cannot pass a comparator.
The Main Idea
Comparabledefines one natural order inside the class withcompareTo().Comparatordefines any number of custom orders outside the class withcompare().
Key points to remember:
Return negative, zero, or positive. Only the sign matters.
Use
Integer.compare()instead of subtraction.Combine comparators with
reversed()andthenComparing().TreeSetandTreeMaptreat a comparison result of 0 as a duplicate.Collections.reverseOrder()turns aPriorityQueueinto a max-heap.
Practice idea: create an Employee class with name, department, and salary. Sort a list of employees by department (A to Z), and within each department by salary from highest to lowest.