Codiqo

Learn Java · lesson 55 of 61 · about 9 minutes

Comparators

Sort lists by any field, in either direction, with tie-breakers.

What you'll learn

  • Sort with a lambda comparator
  • Build comparators with Comparator.comparing
  • Add tie-breakers with thenComparing and flip with reversed

Tomorrow's rota

Next the manager types tomorrow's rota, each shift as a name and hours, like Ada 6, until done. Reading them into record Shift(String name, int hours) is written for you, with Not a shift: Di four for a line that doesn't fit. Your part is the order: the longest shifts first, so whoever opens up is at the top, and shifts of the same length in name order, printed as Rota: Cy 8h Ada 6h Bo 6h Eve 4h.

Telling sort what "in order" means

list.sort(...) takes a Comparator: a lambda (a, b) -> ... that returns a negative number if a comes first, positive if b does, and 0 if they're equal.

Writing that by hand is fiddly, so Comparator.comparing builds one from the thing to compare: Comparator.comparing(String::length) sorts strings by length. String::length is a method reference, a shorter way to write s -> s.length().

Three ways to sort

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>(List.of("banana", "fig", "kiwi", "apple"));
        words.sort(Comparator.naturalOrder());
        System.out.println(words);
        words.sort((a, b) -> a.length() - b.length());
        System.out.println(words);
        words.sort(Comparator.comparing(String::length).reversed());
        System.out.println(words);
    }
}

Output

[apple, banana, fig, kiwi]
[fig, kiwi, apple, banana]
[banana, apple, kiwi, fig]

Sorting records by fields

With a record like Player(String name, int score), Comparator.comparingInt(Player::score) sorts by score. Add .reversed() for highest first, and .thenComparing(Player::name) to break ties by name.

A leaderboard order

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    record Player(String name, int score) {}

    public static void main(String[] args) {
        List<Player> ps = new ArrayList<>(List.of(
            new Player("Cy", 300), new Player("Ada", 510), new Player("Bo", 300)));
        ps.sort(Comparator.comparingInt(Player::score).reversed().thenComparing(Player::name));
        ps.forEach(p -> System.out.println(p.name() + " " + p.score()));
    }
}

Output

Ada 510
Bo 300
Cy 300

Where reversed() goes

Comparator.comparingInt(Shift::hours).reversed().thenComparing(Shift::name) reads left to right: compare the hours, flip that so the most hours come first, and only then add the tie-breaker. Put reversed() at the very end instead and it flips the whole comparator, tie-breaker included, so shifts of the same length come out in reverse name order.

Tip

Java's sort is stable: items that compare as equal keep their original order. That's why sorting by a tie-breaker first and the main field second also works.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.