Stable Sort Preserves Equal Order

Compose multi-key ordering with two sorts: pass one orders the tiebreak key, pass two sorts by the primary, and stable TimSort keeps that tiebreak order.

JavaData Integrity

Code

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

public class LeaderboardRanks {

    record Player(String name, int score, String joinedAt) {}

    public static void main(String[] args) {
        List<Player> board = new ArrayList<>(List.of(
                new Player("kim", 900, "2026-03"),
                new Player("ada", 900, "2026-01"),
                new Player("raj", 750, "2026-04"),
                new Player("mei", 750, "2026-02")));

        // 第一遍:先按次要键(加入时间)排好序
        board.sort(Comparator.comparing(Player::joinedAt));

        // 第二遍:只按主键排。TimSort is stable:同分玩家保留第一遍定下的
        // 先后顺序,两遍排序即合成 "score desc, joinedAt asc" 的多字段排序
        board.sort(Comparator.comparingInt(Player::score).reversed());

        board.forEach(p -> System.out.println(p.score() + " " + p.name() + " " + p.joinedAt()));
        // 同分内部 ada 在 kim 之前、mei 在 raj 之前:该次序来自第一遍而非原始输入
    }
}

What the code does

All of the logic lives in the classes LeaderboardRanks and Player and the function main.

Watch out for

  • Nothing to add to the project before running it.

Using it

Its full declaration is public static void main(String[] args)

Key statements

board.sort(Comparator.comparingInt(Player::score).reversed());
board.sort(Comparator.comparing(Player::joinedAt));

Interactive Tools for This Topic

FAQ

How do you run Stable Sort Preserves Equal Order?
Run the file on its own; every call resolves against the standard surface it already imports.