Stop 08 · Collections & GenericsTopics · 8/10

Comparable vs Comparator

Part of the Java Roadmap

In short

Sort products by price, then by rating, then by name. Sort students by marks, or alphabetically. Java gives you two tools for ordering objects, and knowing when to use each is a classic interview question.

Comparable defines a class's natural order via compareTo(). Comparator defines separate, external orders, and Comparator.comparing() makes multi-field sorting short and readable.

The jaadu, holding a whistle, rearranges a line of schoolchildren from shortest-to-tallest into groups by coloured house sashes.

Think of it like this

Height line vs the teacher's choice

In a school assembly, students line up by height by default. That built-in rule is Comparable, the natural order. On sports day the teacher says "line up by house, then by roll number" instead. That outside rule, given for a specific occasion, is a Comparator.

Watch it happen

Two ways to define order

Comparable

  • Implemented by the class itself
  • One method: compareTo(other)
  • Defines the single natural order
  • Used by Collections.sort(list) and TreeSet by default

Comparator

  • A separate object or lambda
  • One method: compare(a, b)
  • As many orders as you like
  • Chains with comparing, thenComparing, reversed

Give a class Comparable when it has one obvious order. Use Comparators for every other sort.

The big ideas

What you need to know

Negative, zero, positive

compareTo and compare return a negative number if the first comes first, zero if equal, positive if it comes later.

Use Integer.compare

Never return a - b. It can overflow for large values. Integer.compare(a, b) is always correct.

Chain comparators

Comparator.comparing(Product::price).thenComparing(Product::name) sorts by price, then name on ties.

Flip with reversed()

Add .reversed() for descending order, or use Comparator.reverseOrder() for natural order backwards.

See it in code

Walk through the code

java
1import java.util.ArrayList;2import java.util.Comparator;3import java.util.List;4 5public class SortDemo {6    record Product(String name, int priceRupees, double rating)7            implements Comparable<Product> {8        @Override9        public int compareTo(Product other) {10            return Integer.compare(priceRupees, other.priceRupees);11        }12    }13 14    public static void main(String[] args) {15        List<Product> cart = new ArrayList<>(List.of(16            new Product("Kurta", 899, 4.2),17            new Product("Earphones", 1499, 4.6),18            new Product("Diary", 199, 4.6)));19 20        cart.sort(Comparator.naturalOrder());      // cheapest first21        System.out.println(cart.get(0).name());    // Diary22 23        cart.sort(Comparator.comparingDouble(Product::rating).reversed()24                .thenComparing(Product::name));25        cart.forEach(p -> System.out.println(p.name() + " " + p.rating()));26    }27}

1/4The record implements Comparable, so products know how to compare themselves by price.

Natural order by price through Comparable, then a custom order: best rating first, name as the tie-breaker. Prints Diary, Earphones, Kurta.

Save yourself the pain

Common mistakes

Oops

Writing return this.price - other.price; in compareTo.

Do this instead

Use Integer.compare(this.price, other.price). Subtraction can overflow and give the wrong sign.

Oops

Writing a new Comparator class for every sort order.

Do this instead

Use Comparator.comparing with method references and chain thenComparing.

Oops

Making compareTo disagree with equals.

Do this instead

Keep them consistent. A TreeSet treats compareTo == 0 as a duplicate and drops it.

Your mission

Sort the merit list

~25 min

Quick check

You cannot edit a class from a library but need to sort its objects. What do you use?

Go deeper

  1. 1Make a Student class Comparable by roll number.
  2. 2Sort the same list by name, then by marks, with Comparator.comparing().thenComparing().
  3. 3Sort in reverse order with Comparator.reversed().

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge