Custom order with Comparator
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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")); }}Natural: [Agra, Bengaluru, Chennai, Goa, Pune] By length: [Goa, Agra, Pune, Chennai, Bengaluru] Goa vs Pune: -1
What this code does
Stringalready has a natural order (A to Z), and you cannot edit theStringclass. AComparator<String>is a separate object that holds a different order.compare(a, b)follows the same sign rules ascompareTo.list.sort(cmp)andCollections.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.
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.
- A named class:
class LengthComparator implements Comparator<String>. Useful when it is reused in many places. - An anonymous class:
new Comparator<Student>() { public int compare(...) {...} }, written right where it is needed. - A lambda:
(a, b) -> Integer.compare(a.getMarks(), b.getMarks()).Comparatoris a functional interface, so this works. - 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
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); }}By marks: [Rohan(92), Kavya(85), Aarav(78)] By name: [Aarav(78), Kavya(85), Rohan(92)]
What this code does
Studenthas 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.Comparatorhas 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).
Example 3 · Comparator.comparing builds it from a field
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)); }}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.comparingIntis the same forintkeys and skips boxing them intoInteger.reversed()returns a new comparator with the opposite order.Collections.maxandCollections.minalso accept a comparator.
Example 4 · Ready-made comparators for Strings and numbers
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); }}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
Zoyacomes beforeaditi.String.CASE_INSENSITIVE_ORDERcompares the letters without caring about case. Comparator.naturalOrder()andComparator.reverseOrder()work for anyComparabletype, such asStringorInteger.
Example 5 · thenComparing: a second key for ties
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); }}[CSK:Dube, CSK:Jadeja, MI:Bumrah, MI:Rohit, RCB:Kohli] [CSK:Dube, CSK:Jadeja, MI:Bumrah, MI:Rohit, RCB:Kohli]
What this code does
thenComparingis 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::getTeamis a method reference, a shorter way to writep -> 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
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()); }}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 errorWhat this code does
- Java guesses the lambda's parameter type from where the result goes. Here the result of
comparing(...)goes into.reversed(), not intosort, so Java cannot see thatsis aStudent. It falls back toObject, which has nogetCgpa(). - The fix is to name the type:
Comparator.comparing((Student s) -> s.getCgpa()).reversed(), or to storeComparator<Student> byCgpa = Comparator.comparing(s -> s.getCgpa());first and then callbyCgpa.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.
Error
SortOrders.java:8: error: cannot find symbol
orders.sort(Comparator.comparing(o -> o.getTotal()).reversed());
^
location: variable o of type ObjectComparable 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.
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); }}[Agra, Delhi, Mumbai, Pune] [Agra, Pune, Delhi, Mumbai]
Comparable: inside the class, methodcompareTo(T other), one order, packagejava.lang.Comparator: separate object, methodcompare(T a, T b), as many orders as you like, packagejava.util.Comparablechanges the class;Comparatorleaves it untouched, so it works forStringand 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