01 / 21

Writing
Comparators

Learn to define custom sorting logic in Java by implementing the Comparator interface: control how objects are ordered in collections and arrays.

AP Computer Science A Java

Why Do We Need Custom Sorting?

Java's Collections.sort() and Arrays.sort() know how to sort numbers and strings by default. But what about sorting a list of Student objects by GPA? Or a list of Song objects by duration?

Think of a Comparator as a judge at a competition: it looks at two contestants and decides who ranks higher.

The Comparator Interface

java.util.Comparator<T> is a functional interface with one essential method:

int compare(T a, T b)
\(< 0\)
a should come before b
0
a and b are equal in order
\(> 0\)
a should come after b

How compare() Drives Sorting

a b compare(a,b) negative a before b zero equal order positive b before a

The compare() Contract

Your compare method must follow a simple rule: return an integer whose sign indicates order.

// Ascending order by some numeric field: return a.field - b.field; // Descending order: return b.field - a.field; // Ascending by String (alphabetical): return a.getName().compareTo(b.getName());

Comparable vs Comparator

Comparable Comparator
Package java.lang java.util
Method compareTo(T o) compare(T a, T b)
Where defined Inside the class itself In a separate class or lambda
Sort orders One "natural" order Unlimited custom orders
Modifies class? Yes No

How to Write a Comparator

1
Identify the type you are sorting (e.g., Student) and the field to sort by (e.g., gpa).
2
Create a class that implements Comparator<Student>, or write a lambda expression.
3
Override compare(Student a, Student b). Return a negative, zero, or positive integer.
4
Pass it to Collections.sort(list, comparator) or Arrays.sort(arr, comparator).

Example 1: Named Class

Sort a list of students by age in ascending order:

import java.util.*; class AgeComparator implements Comparator<Student> { @Override public int compare(Student a, Student b) { return a.getAge() - b.getAge(); } } // Usage: List<Student> roster = getRoster(); Collections.sort(roster, new AgeComparator());

Example 2: Lambda Shorthand

The same sort using a lambda expression: no separate class needed.

List<Student> roster = getRoster(); // Sort by age ascending, one line: Collections.sort(roster, (a, b) -> a.getAge() - b.getAge()); // Or even shorter with a method reference: roster.sort(Comparator.comparingInt(Student::getAge));
Lambda
Great for quick, one-off sorts inline where the logic is simple.
Named Class
Better when you reuse the same comparator in multiple places.

Example 3: Sorting by Name

Sort students alphabetically by last name. Strings already implement Comparable, so delegate:

Collections.sort(roster, (a, b) -> a.getLastName().compareTo(b.getLastName()) );

For reverse alphabetical (Z to A), simply swap a and b:

(a, b) -> b.getLastName().compareTo(a.getLastName())

Example 4: Multi-Key Sorting

Sort by GPA descending, then break ties by last name ascending:

Collections.sort(roster, (a, b) -> { int cmp = Double.compare(b.getGpa(), a.getGpa()); if (cmp != 0) return cmp; return a.getLastName().compareTo(b.getLastName()); });

Ascending vs Descending

Ascending a.field - b.field 2 5 9 Descending b.field - a.field 9 5 2

Safer Comparison with Integer.compare

The subtraction trick a - b can overflow with extreme values. Java provides safe alternatives:

// Safe integer comparison: Integer.compare(a.getAge(), b.getAge()) // Safe double comparison: Double.compare(a.getGpa(), b.getGpa())
a - b
Fast but can overflow if values are near Integer.MAX_VALUE or MIN_VALUE.
Integer.compare
Always safe. Handles edge cases correctly. Preferred for production code.

Plugging In Your Comparator

UNSORTED 5 2 8 Collections.sort(list, comp) calls compare() on pairs SORTED 2 5 8 Your Comparator
// Two equivalent ways to sort with a comparator: Collections.sort(list, myComparator); list.sort(myComparator);

Common Mistakes

✕ Wrong Generic Type
Writing Comparator<Object> instead of Comparator<Student> forces casting and loses type safety.
✕ Reversed Return Logic
Returning b - a when you wanted ascending, or a - b when you wanted descending.
✕ Integer Overflow
Using a - b with extreme int values. Use Integer.compare(a, b) instead.

Summary Cheat Sheet

Goal Code Pattern
Ascending (int) Integer.compare(a.x, b.x)
Descending (int) Integer.compare(b.x, a.x)
Ascending (double) Double.compare(a.x, b.x)
Alphabetical (String) a.s.compareTo(b.s)
Reverse alphabetical b.s.compareTo(a.s)
Multi-key Compare primary, if 0 compare secondary

Question 1 of 5

What does compare(a, b) return when a should come before b?

Question 2 of 5

Which expression sorts students by age in descending order?

Question 3 of 5

What is the key difference between Comparable and Comparator?

Question 4 of 5

How does this comparator sort students?

Question 5 of 5

Why is Integer.compare(a, b) preferred over a - b?