Lesson 31: Comparable & Comparator

01 Aug 2026 1 min Swarnil Singhai

Comparable defines a class's single 'natural' order; Comparator defines any number of alternative orderings without touching the class.

Real-time example

A Product list sorts naturally by SKU (Comparable), but the storefront also needs to sort the same list by price (Comparator) for a 'sort by price' filter.

class Product implements Comparable<Product> {
    String sku; double price;
    Product(String sku, double price) { this.sku = sku; this.price = price; }
    public int compareTo(Product o) { return sku.compareTo(o.sku); }
}
List<Product> products = new ArrayList<>(List.of(
    new Product("B", 20), new Product("A", 50)));

products.sort(Comparator.comparingDouble(p -> p.price));
// sorted by price, without changing Product's natural order

What's happening

Collections.sort(products) uses compareTo (natural order); passing a Comparator overrides it just for that call.

Use Comparator.comparing(...).thenComparing(...) to build multi-level sorts without writing a manual compareTo.

Advertisement