Advanced sorting
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A Comparator can be assembled from ready-made pieces:
record Player(String name, int score, int level) { }
players.sort(Comparator.comparingInt(Player::score)); // by score
players.sort(Comparator.comparingInt(Player::score).reversed()); // descending
players.sort(Comparator.comparingInt(Player::level).reversed()
.thenComparing(Player::name)); // on a tie — by name
players.sort(Comparator.comparing(Player::name, String.CASE_INSENSITIVE_ORDER));
Comparator.nullsFirst(Comparator.naturalOrder()) // nulls first
You can make your own class comparable "by default" — implements Comparable<Player> and the method
compareTo; the result is < 0 if this is smaller, 0 if they're equal, > 0 if it's bigger. Comparing numbers by subtraction
(a - b) is dangerous — it can overflow; use Integer.compare(a, b).
Task. A leaderboard: lines of nickname score level. Print the players sorted by score
in descending order, with equal scores — by level in ascending order, then by nickname ignoring case. The line format:
place. nickname score (lvl N). On the last line print Most experienced: nickname: the player with the highest level
(on a tie — the one higher in the table).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.