Codectionary / Developer documentation / Java

Sorting by Multiple Fields

Sort by one key and use a second key only when the first values compare equally.

What it is and why to use it

A leaderboard or directory often needs more than one ordering rule. Comparator.comparingInt chooses a numeric key and thenComparing adds a tie-breaker. Chaining keeps the sort policy separate from the data type instead of forcing every use to share one natural order.

How it works

The comparator first orders players by score ascending. reversed changes that comparator to descending. thenComparing adds name ascending only for equal scores. Placing reversed at the very end would reverse the entire combined order, including the name tie-breaker.

Common mistakes and limitations

Do not compare arbitrary integer values by subtraction, which can overflow. Handle nullable keys explicitly if your data permits them. Java’s String natural order is not locale-aware human name collation.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

Comparator.comparingInt(Player::score).reversed().thenComparing(Player::name)

Examples

Sorting by Multiple Fields

Complete Main.java example — Java 17 or later, without preview features.

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> players = new ArrayList<>(List.of(
        new Player("James", 8), new Player("John", 10), new Player("Alex", 10)));
    players.sort(Comparator.comparingInt(Player::score).reversed()
        .thenComparing(Player::name));
    for (Player player : players) System.out.println(player.name());
  }
}
  1. John and Alex share the highest score and therefore precede James.
  2. The name comparator breaks their tie, putting Alex before John.
  3. sort changes the mutable list; printing names exposes the resulting order without relying on a record’s default textual format. This policy could drive a leaderboard.
  4. Expected output: Alex John James

Best practices

  • Make tie-breakers explicit.
  • Put reversed immediately after the ordering component you intend to reverse.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading