Java Tutorial · Collections · Lesson 28 of 37

Java Sorting and Comparators

Sort with Comparable, Comparator, and chained comparators.

Natural order: Comparable

Classes like String and Integer have a natural order. Your own classes get one by implementing Comparable<T>.

Custom order: Comparator

A Comparator defines an order from outside the class. Build them with Comparator.comparing() and chain with thenComparing() and reversed():

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

public class Main {
    public static void main(String[] args) {
        List<Player> players = new ArrayList<>(List.of(
            new Player("Zoe", 1200), new Player("Al", 1500), new Player("Bo", 1200)));
        players.sort(Comparator.comparingInt(Player::rating).reversed().thenComparing(Player::name));
        players.forEach(p -> System.out.println(p.name() + " " + p.rating()));
        List<String> words = new ArrayList<>(List.of("banana", "Fig", "apple", "kiwi"));
        words.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println(words);
        words.sort(Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()));
        System.out.println(words);
    }

    record Player(String name, int rating) {}
}

Output

Al 1500
Bo 1200
Zoe 1200
[apple, banana, Fig, kiwi]
[Fig, kiwi, apple, banana]

Run this on your computer — see “Get Started” for setup.

List.sort() and Collections.sort() are stable: items that compare equal keep their original order.

Test yourself

Which method reverses a Comparator's order?

  1. reverse()
  2. reversed()
  3. descending()
  4. flip()
Show answer

Answer: reversed()

Practice next