Skip to lesson

Custom order with Comparator

A Comparator is a separate object that compares two other objects. It lets you sort the same data in many orders, by name, by price or by length, without changing the class being sorted.

Why one natural order is not enough

Comparator<T> is an interface in java.util with one method, int compare(T a, T b). It is a separate object that defines an order, so one class can be sorted in many ways without changing the class.

Comparable gives a class exactly one order, but real apps need more: a marks list by marks, by name or by roll number. Sometimes you cannot change the class at all, such as String.

Example 1 · A Comparator class: sort cities by length

LengthSortDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;
class LengthComparator implements Comparator<String> {    @Override    public int compare(String a, String b) {        return Integer.compare(a.length(), b.length());    }}
public class LengthSortDemo {    public static void main(String[] args) {        List<String> cities = new ArrayList<>();        cities.add("Bengaluru");        cities.add("Pune");        cities.add("Goa");        cities.add("Chennai");        cities.add("Agra");
        Collections.sort(cities);        System.out.println("Natural:   " + cities);
        cities.sort(new LengthComparator());        System.out.println("By length: " + cities);
        LengthComparator cmp = new LengthComparator();        System.out.println("Goa vs Pune: " + cmp.compare("Goa", "Pune"));    }}
Output
Natural:   [Agra, Bengaluru, Chennai, Goa, Pune]
By length: [Goa, Agra, Pune, Chennai, Bengaluru]
Goa vs Pune: -1

What this code does

  • String already has a natural order (A to Z), and you cannot edit the String class. A Comparator<String> is a separate object that holds a different order.
  • compare(a, b) follows the same sign rules as compareTo. list.sort(cmp) and Collections.sort(list, cmp) both accept it. Agra and Pune tie on length and keep their earlier order.

A Comparator<T> from java.util solves both problems. Its one abstract method is int compare(T a, T b), with the same sign rules as compareTo: negative if a comes first, zero for a tie, positive if a comes after.

Pass a comparator with list.sort(cmp) or Collections.sort(list, cmp). list.sort(null) means natural order.

Four ways to write one

Comparator.comparing is a static method that builds a Comparator from a key extractor: a lambda that pulls out the value to sort by, such as p -> p.getPrice(). The key must be Comparable.

All four create the same kind of object. Pick the shortest that is still easy to read.

  1. A named class: class LengthComparator implements Comparator<String>. Useful when it is reused in many places.
  2. An anonymous class: new Comparator<Student>() { public int compare(...) {...} }, written right where it is needed.
  3. A lambda: (a, b) -> Integer.compare(a.getMarks(), b.getMarks()). Comparator is a functional interface, so this works.
  4. A factory method: Comparator.comparingInt(s -> s.getMarks()). You give only the sort key; Java writes the comparison.

Example 2 · Anonymous class and lambda: less code

ThreeWaysDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
class Student {    private String name;    private int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }
    String getName() {        return name;    }
    int getMarks() {        return marks;    }
    @Override    public String toString() {        return name + "(" + marks + ")";    }}
public class ThreeWaysDemo {    public static void main(String[] args) {        List<Student> list = new ArrayList<>();        list.add(new Student("Rohan", 92));        list.add(new Student("Aarav", 78));        list.add(new Student("Kavya", 85));
        // 1. anonymous class: highest marks first        list.sort(new Comparator<Student>() {            @Override            public int compare(Student a, Student b) {                return Integer.compare(b.getMarks(), a.getMarks());            }        });        System.out.println("By marks: " + list);
        // 2. lambda: by name, A to Z        list.sort((a, b) -> a.getName().compareTo(b.getName()));        System.out.println("By name:  " + list);    }}
Output
By marks: [Rohan(92), Kavya(85), Aarav(78)]
By name:  [Aarav(78), Kavya(85), Rohan(92)]

What this code does

  • Student has no natural order at all, and it does not need one. Each sort passes its own comparator, so one class can be sorted many ways.
  • Comparator has one abstract method, so it is a functional interface, and a lambda (a, b) -> ... can stand for it. The lambda is the anonymous class without the boilerplate.

Reverse, chain and ready-made orders

thenComparing adds a second sort key to a Comparator. The second key is used only when the first key says two items are equal, so it breaks ties.

reversed() returns a comparator with the opposite order. thenComparing(...) adds a second key, used only when the first one ties. Both return new comparators, so you can chain them: byTeam.thenComparing(byName).

A comparator chain, by price then by name. Start: Mouse 700, Hub 1500, Pad 150, Cable 700. After comparing by price: Pad 150, Mouse 700, Cable 700, Hub 1500, where Mouse and Cable tie at 700. After thenComparing by name, the tie is settled: Pad 150, Cable 700, Mouse 700, Hub 1500.

Example 3 · Comparator.comparing builds it from a field

CatalogSortDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;
class Product {    private String name;    private int price;
    Product(String name, int price) {        this.name = name;        this.price = price;    }
    String getName() {        return name;    }
    int getPrice() {        return price;    }
    @Override    public String toString() {        return name + " " + price;    }}
public class CatalogSortDemo {    public static void main(String[] args) {        List<Product> catalog = new ArrayList<>();        catalog.add(new Product("Monitor", 11000));        catalog.add(new Product("Cable", 150));        catalog.add(new Product("Keyboard", 1500));        catalog.add(new Product("Mouse", 700));
        Comparator<Product> byPrice = Comparator.comparingInt(i -> i.getPrice());        Comparator<Product> byName = Comparator.comparing(i -> i.getName());
        catalog.sort(byPrice);        System.out.println("Cheapest first: " + catalog);        catalog.sort(byPrice.reversed());        System.out.println("Costliest first: " + catalog);        catalog.sort(byName);        System.out.println("By name: " + catalog);        System.out.println("Costliest item: " + Collections.max(catalog, byPrice));    }}
Output
Cheapest first: [Cable 150, Mouse 700, Keyboard 1500, Monitor 11000]
Costliest first: [Monitor 11000, Keyboard 1500, Mouse 700, Cable 150]
By name: [Cable 150, Keyboard 1500, Monitor 11000, Mouse 700]
Costliest item: Monitor 11000

What this code does

  • Comparator.comparing(i -> i.getName()) takes a lambda that pulls out the sort key and builds the whole comparator for you. comparingInt is the same for int keys and skips boxing them into Integer.
  • reversed() returns a new comparator with the opposite order. Collections.max and Collections.min also accept a comparator.

Example 4 · Ready-made comparators for Strings and numbers

ReadyMadeDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class ReadyMadeDemo {    public static void main(String[] args) {        List<String> names = new ArrayList<>();        names.add("kavya");        names.add("Bhavya");        names.add("aditi");        names.add("Zoya");
        names.sort(Comparator.naturalOrder());        System.out.println("Natural:          " + names);        names.sort(String.CASE_INSENSITIVE_ORDER);        System.out.println("Ignoring case:    " + names);        names.sort(Comparator.reverseOrder());        System.out.println("Reverse natural:  " + names);
        List<Integer> scores = new ArrayList<>();        scores.add(64);        scores.add(98);        scores.add(71);        scores.sort(Comparator.reverseOrder());        System.out.println("Scores high first: " + scores);    }}
Output
Natural:          [Bhavya, Zoya, aditi, kavya]
Ignoring case:    [aditi, Bhavya, kavya, Zoya]
Reverse natural:  [kavya, aditi, Zoya, Bhavya]
Scores high first: [98, 71, 64]

What this code does

  • In natural order every capital letter comes before every small letter, so Zoya comes before aditi. String.CASE_INSENSITIVE_ORDER compares the letters without caring about case.
  • Comparator.naturalOrder() and Comparator.reverseOrder() work for any Comparable type, such as String or Integer.

Example 5 · thenComparing: a second key for ties

SquadDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
class Player {    private String team;    private String name;
    Player(String team, String name) {        this.team = team;        this.name = name;    }
    String getTeam() {        return team;    }
    String getName() {        return name;    }
    @Override    public String toString() {        return team + ":" + name;    }}
public class SquadDemo {    public static void main(String[] args) {        List<Player> squad = new ArrayList<>();        squad.add(new Player("MI", "Rohit"));        squad.add(new Player("CSK", "Jadeja"));        squad.add(new Player("MI", "Bumrah"));        squad.add(new Player("RCB", "Kohli"));        squad.add(new Player("CSK", "Dube"));
        Comparator<Player> byTeamThenName =                Comparator.comparing((Player p) -> p.getTeam())                          .thenComparing(p -> p.getName());        squad.sort(byTeamThenName);        System.out.println(squad);
        // shorter form of the same thing: a method reference        squad.sort(Comparator.comparing(Player::getTeam).thenComparing(Player::getName));        System.out.println(squad);    }}
Output
[CSK:Dube, CSK:Jadeja, MI:Bumrah, MI:Rohit, RCB:Kohli]
[CSK:Dube, CSK:Jadeja, MI:Bumrah, MI:Rohit, RCB:Kohli]

What this code does

  • thenComparing is used only when the first comparator says "tie". Players are grouped by team, and inside a team they are sorted by name.
  • (Player p) -> names the type, so the chain compiles. Player::getTeam is a method reference, a shorter way to write p -> p.getTeam(); a later section covers it, and the lambda form is always fine.

Java also gives ready-made ones: Comparator.naturalOrder(), Comparator.reverseOrder() and String.CASE_INSENSITIVE_ORDER.

One shorter form is worth knowing: Comparator.comparing(Player::getName) is a method reference, the same as p -> p.getName(). A later section covers method references; the lambda form always works.

The reversed() trap

reversed() is a Comparator method that returns a new comparator with the opposite order. Called on a chain, it flips everything written before it.

Java works out a lambda's parameter type from where the lambda is used. In list.sort(Comparator.comparing(s -> s.getCgpa())), sort wants a Comparator<Student>, so s is a Student.

Example 6 · Trap: comparing(...).reversed() loses the type

ReversedTrapDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
class Student {    private String name;    private double cgpa;
    Student(String name, double cgpa) {        this.name = name;        this.cgpa = cgpa;    }
    double getCgpa() {        return cgpa;    }}
public class ReversedTrapDemo {    public static void main(String[] args) {        List<Student> list = new ArrayList<>();        list.add(new Student("Aarav", 8.4));        list.add(new Student("Priya", 9.1));        list.sort(Comparator.comparing(s -> s.getCgpa()).reversed());    }}
Sample compiler output
ReversedTrapDemo.java:24: error: cannot find symbol
        list.sort(Comparator.comparing(s -> s.getCgpa()).reversed());
                                             ^
  symbol:   method getCgpa()
  location: variable s of type Object
1 error

What this code does

  • Java guesses the lambda's parameter type from where the result goes. Here the result of comparing(...) goes into .reversed(), not into sort, so Java cannot see that s is a Student. It falls back to Object, which has no getCgpa().
  • The fix is to name the type: Comparator.comparing((Student s) -> s.getCgpa()).reversed(), or to store Comparator<Student> byCgpa = Comparator.comparing(s -> s.getCgpa()); first and then call byCgpa.reversed().

Add .reversed() at the end and that link is lost. Java must type comparing(...) on its own, finds nothing, and uses Object. The error is "cannot find symbol ... variable s of type Object". Fix it by naming the type, (Student s) -> s.getCgpa(), or by storing the comparator in a Comparator<Student> variable first.

Fix the error

Fix the comparator line

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

Show the biggest orders first.

import java.util.*;
public class SortOrders {
public static void main(String[] args) {
List<Order> orders = new ArrayList<>();
orders.add(new Order("A101", 2500.0));
orders.add(new Order("A102", 9100.0));
orders.sort(Comparator.comparing(o -> o.getTotal()).reversed());
}
}

Error

SortOrders.java:8: error: cannot find symbol
        orders.sort(Comparator.comparing(o -> o.getTotal()).reversed());
                                               ^
  location: variable o of type Object

Comparable or Comparator?

Use both together. Give a class a natural order with Comparable when one order is obvious, such as a date or a version number. Add comparators for every other order.

TwoOrders.javaJava
import java.util.*;
public class TwoOrders {    public static void main(String[] args) {        List<String> cities = new ArrayList<>(List.of("Pune", "Delhi", "Agra", "Mumbai"));        cities.sort(null);        System.out.println(cities);        cities.sort(Comparator.comparingInt(c -> c.length()));        System.out.println(cities);    }}
Output
[Agra, Delhi, Mumbai, Pune]
[Agra, Pune, Delhi, Mumbai]
  • Comparable: inside the class, method compareTo(T other), one order, package java.lang.
  • Comparator: separate object, method compare(T a, T b), as many orders as you like, package java.util.
  • Comparable changes the class; Comparator leaves it untouched, so it works for String and library classes.
  • Sorting with no comparator uses Comparable; passing a comparator overrides it for that one sort.

Next step

Check your understanding

12 quick questions