Skip to lesson

Sorting real data

Real data is rarely sorted by one field. A merit list is sorted by marks, then by name; a leaderboard by points, then time; a timetable by date, then slot. Java builds these orders by chaining comparators, one key at a time.

Sorting by more than one key

A multi-key sort compares two items by a first key, and only when they tie does a second key decide, then a third, and so on. In Java you build it by chaining comparators with thenComparing.

A multi-key sort compares the first key. Only when two items tie on it does the second key decide, and so on. Think of a dictionary: first letters decide, and the second letter matters only when the first letters match.

Example 1 · Marks high to low, then name A to Z

MeritListDemo.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 MeritListDemo {    public static void main(String[] args) {        List<Student> list = new ArrayList<>();        list.add(new Student("Rohan", 85));        list.add(new Student("Aarav", 92));        list.add(new Student("Priya", 85));        list.add(new Student("Kavya", 78));        list.add(new Student("Divya", 92));
        Comparator<Student> merit = Comparator                .comparingInt((Student s) -> s.getMarks()).reversed()                .thenComparing(s -> s.getName());        list.sort(merit);
        for (Student s : list) {            System.out.println(s);        }    }}
Output
Aarav 92
Divya 92
Priya 85
Rohan 85
Kavya 78

What this code does

  • The first key, marks, is compared first, and reversed() right after it makes it high to low. The second key, name, is used only to break ties: Aarav and Divya both have 92, so A comes before D.
  • reversed() here applies only to what comes before it in the chain, which is the marks comparator. The name part added afterwards stays A to Z.

In Java the chain reads like the rule: Comparator.comparingInt((Student s) -> s.getMarks()).reversed().thenComparing(s -> s.getName()). Use thenComparingInt or thenComparingDouble for number keys. Write the type in the first lambda, (Student s), so the whole chain compiles.

Order of execution

How a two-key comparator decides

Tap the steps in the order the comparator does them.

Comparator<Product> cmp = Comparator
.comparingInt((Product p) -> p.getPrice())
.thenComparing(p -> p.getName());
// compare Mouse (700) with Cable (700)
Add a last key that is unique, such as name or roll number, so ties always print in the same order.

The direction of each key

reversed() flips the whole comparator it is called on. Called right after the first key, it flips only that key. Called at the end of a chain, it flips every key: names then come out Z to A inside each tie.

Example 2 · Trap: reversed() at the end flips every key

ReversedEndDemo.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 ReversedEndDemo {    public static void main(String[] args) {        List<Student> list = new ArrayList<>();        list.add(new Student("Rohan", 85));        list.add(new Student("Aarav", 92));        list.add(new Student("Priya", 85));        list.add(new Student("Divya", 92));
        Comparator<Student> wrong = Comparator                .comparingInt((Student s) -> s.getMarks())                .thenComparing(s -> s.getName())                .reversed();        list.sort(wrong);        System.out.println("reversed() at the end: " + list);
        Comparator<Student> right = Comparator                .comparingInt((Student s) -> s.getMarks()).reversed()                .thenComparing(s -> s.getName());        list.sort(right);        System.out.println("reversed() after marks: " + list);
        Comparator<Student> perKey = Comparator                .comparingInt((Student s) -> s.getMarks())                .thenComparing(s -> s.getName(), Comparator.reverseOrder());        list.sort(perKey);        System.out.println("marks up, names Z-A:   " + list);    }}
Output
reversed() at the end: [Divya 92, Aarav 92, Rohan 85, Priya 85]
reversed() after marks: [Aarav 92, Divya 92, Priya 85, Rohan 85]
marks up, names Z-A:   [Rohan 85, Priya 85, Divya 92, Aarav 92]

What this code does

  • reversed() turns around the whole comparator it is called on. At the end of the chain it reverses the names too, so Divya comes before Aarav.
  • To set a direction for one key only, put reversed() straight after that key, or pass a second comparator to thenComparing, like Comparator.reverseOrder().

To reverse a later key only, pass a second comparator: thenComparing(s -> s.getName(), Comparator.reverseOrder()). Or build each key as its own typed comparator, reverse the ones you need, and chain them: byPoints.reversed().thenComparing(byNrr.reversed()).

Find the bug

Find the wrong line

Each sort should come out as described. Tap the wrong line, then check the fix.

Highest price first, and A to Z for equal prices. Tied names come out Z to A.

Round 1 of 2

Stable sorting

A stable sort keeps items that compare as equal in the same order they had before sorting. Java's sort for objects, List.sort and Collections.sort, is stable.

Java's object sort is stable: items that compare as equal keep the order they had before the sort. Sorting by plan keeps members in joining order within each plan.

A stable sort. Before sorting by price: Mouse 700, Hub 1500, Cable 700, Pad 150. After: Pad 150, Mouse 700, Cable 700, Hub 1500. Mouse and Cable have the same price of 700, so they keep their old order and Mouse stays before Cable.

Example 3 · Stable sort: ties keep their old order

StableSortDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
enum Plan { GOLD, SILVER, BASIC }
class Member {    private String name;    private Plan plan;
    Member(String name, Plan plan) {        this.name = name;        this.plan = plan;    }
    Plan getPlan() {        return plan;    }
    @Override    public String toString() {        return name + "(" + plan + ")";    }}
public class StableSortDemo {    public static void main(String[] args) {        // already in joining order        List<Member> gym = new ArrayList<>();        gym.add(new Member("Rohan", Plan.BASIC));        gym.add(new Member("Aarav", Plan.GOLD));        gym.add(new Member("Zoya", Plan.SILVER));        gym.add(new Member("Kavya", Plan.GOLD));        gym.add(new Member("Arjun", Plan.BASIC));        gym.add(new Member("Divya", Plan.GOLD));        System.out.println("Joined: " + gym);
        gym.sort(Comparator.comparing(m -> m.getPlan()));        System.out.println("By plan: " + gym);    }}
Output
Joined: [Rohan(BASIC), Aarav(GOLD), Zoya(SILVER), Kavya(GOLD), Arjun(BASIC), Divya(GOLD)]
By plan: [Aarav(GOLD), Kavya(GOLD), Divya(GOLD), Zoya(SILVER), Rohan(BASIC), Arjun(BASIC)]

What this code does

  • Enums have a natural order: the order the constants are declared in, so GOLD comes first. The comparator looks only at the plan.
  • Java's object sort is stable: members with the same plan stay in their joining order (Aarav, Kavya, Divya). You get "by plan, then by joining date" without writing a second key.

Sorting complaints by priority keeps them in arrival order within each priority. This is a gift, not an accident: List.sort and Collections.sort promise it in their documentation. They use TimSort, a merge-sort-based method that takes O(n log n) time and is very fast on data that is already partly sorted.

When data has nulls

Forms and files often leave a field empty, and in Java that is null. Natural order and comparing call compareTo, so one null makes the whole sort throw NullPointerException.

Example 4 · Mistake: a null field crashes the sort

NullCityDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
class Student {    private String name;    private String city;
    Student(String name, String city) {        this.name = name;        this.city = city;    }
    String getCity() {        return city;    }
    @Override    public String toString() {        return name + "-" + city;    }}
public class NullCityDemo {    public static void main(String[] args) {        List<Student> list = new ArrayList<>();        list.add(new Student("Aarav", "Pune"));        list.add(new Student("Priya", null));        // city not filled in the form        list.add(new Student("Rohan", "Chennai"));
        list.sort(Comparator.comparing(s -> s.getCity()));        System.out.println(list);    }}
Sample output
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because the return value of "java.util.function.Function.apply(Object)" is null
	at java.base/java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:473)
	at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
	at java.base/java.util.TimSort.sort(TimSort.java:220)
	at java.base/java.util.Arrays.sort(Arrays.java:1307)
	at java.base/java.util.ArrayList.sort(ArrayList.java:1721)
	at NullCityDemo.main(NullCityDemo.java:31)

What this code does

  • comparing calls compareTo on the cities. When one city is null, there is no object to call it on, and the sort stops with NullPointerException deep inside the library code.
  • The last line of the trace points to our sort call on line 31. Missing values like this are common in real data from forms and files.

Example 5 · Fix: nullsFirst and nullsLast

NullsLastDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
class Student {    private String name;    private String city;
    Student(String name, String city) {        this.name = name;        this.city = city;    }
    String getName() {        return name;    }
    String getCity() {        return city;    }
    @Override    public String toString() {        return name + "-" + city;    }}
public class NullsLastDemo {    public static void main(String[] args) {        List<Student> list = new ArrayList<>();        list.add(new Student("Aarav", "Pune"));        list.add(new Student("Priya", null));        list.add(new Student("Rohan", "Chennai"));        list.add(new Student("Kavya", null));
        Comparator<Student> byCity = Comparator.comparing(                (Student s) -> s.getCity(),                Comparator.nullsLast(Comparator.naturalOrder()));        list.sort(byCity.thenComparing(s -> s.getName()));        System.out.println(list);
        List<String> names = new ArrayList<>();        names.add("Rohan");        names.add(null);        names.add("Aarav");        names.sort(Comparator.nullsFirst(Comparator.naturalOrder()));        System.out.println(names);    }}
Output
[Rohan-Chennai, Aarav-Pune, Kavya-null, Priya-null]
[null, Aarav, Rohan]

What this code does

  • Comparator.nullsLast(...) wraps another comparator: null goes to the end, and real values use the inner comparator. Here it is used as the second argument of comparing, so it applies to the city key.
  • nullsFirst puts null at the start. It works on whole elements too, as in the names list. Priya and Kavya tie on null, so thenComparing orders them by name.

Comparator.nullsFirst(cmp) and Comparator.nullsLast(cmp) wrap another comparator and decide where nulls go. Use them on whole elements, names.sort(Comparator.nullsLast(Comparator.naturalOrder())), or on one key, as the second argument of comparing.

Rankings and leaderboards

sort changes the list itself. If the original order matters (a register, a joining list), sort a copy: new ArrayList<>(original). List.copyOf will not do, because it cannot be changed.

Example 6 · A quiz leaderboard with shared ranks

LeaderboardDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
class Contestant {    private String name;    private int points;    private int seconds;
    Contestant(String name, int points, int seconds) {        this.name = name;        this.points = points;        this.seconds = seconds;    }
    String getName() {        return name;    }
    int getPoints() {        return points;    }
    int getSeconds() {        return seconds;    }}
public class LeaderboardDemo {    public static void main(String[] args) {        List<Contestant> registered = new ArrayList<>();        registered.add(new Contestant("Rohan", 80, 410));        registered.add(new Contestant("Aarav", 95, 520));        registered.add(new Contestant("Priya", 95, 480));        registered.add(new Contestant("Kavya", 80, 410));        registered.add(new Contestant("Divya", 70, 300));        registered.add(new Contestant("Arjun", 95, 480));
        Comparator<Contestant> board = Comparator                .comparingInt((Contestant c) -> c.getPoints()).reversed()   // more points first                .thenComparingInt(c -> c.getSeconds())                       // then faster first                .thenComparing(c -> c.getName());
        List<Contestant> ranked = new ArrayList<>(registered);   // keep the original        ranked.sort(board);
        System.out.println("Rank  Name   Points  Time");        int rank = 0;        for (int i = 0; i < ranked.size(); i++) {            Contestant c = ranked.get(i);            if (i == 0 || !sameScore(ranked.get(i - 1), c)) {                rank = i + 1;            }            System.out.println(String.format("%-5d %-6s %6d %5ds", rank, c.getName(), c.getPoints(), c.getSeconds()));        }        System.out.println("First to register: " + registered.get(0).getName());    }
    static boolean sameScore(Contestant a, Contestant b) {        return a.getPoints() == b.getPoints() && a.getSeconds() == b.getSeconds();    }}
Output
Rank  Name   Points  Time
1     Arjun      95   480s
1     Priya      95   480s
3     Aarav      95   520s
4     Kavya      80   410s
4     Rohan      80   410s
6     Divya      70   300s
First to register: Rohan

What this code does

  • Three keys decide the order: points (high first), time (low first), then name, only so that ties print in a fixed order. The sort works on a copy, so registered keeps its original order.
  • Ranks follow the usual contest rule: people with the same points and time share a rank, and the next rank skips ahead (1, 1, 3, …). sameScore checks only points and time, because the name is not part of the score.

For ranks, walk the sorted list with an index. When an item has the same score as the one above, it keeps that rank; otherwise its rank is index + 1. Ties then share a rank and the next rank skips ahead: 1, 2, 2, 4. This is the rule most exams and contests use.

Next step

Check your understanding

12 quick questions