We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// Checker class that implements Comparator
class Checker implements Comparator {
public int compare(Player a, Player b) {
// First sort by descending score
if (a.score != b.score) {
return b.score - a.score; // higher score comes first
}
// If scores are equal, sort alphabetically by name
return a.name.compareTo(b.name);
}
}
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
Player[] players = new Player[n];
for (int i = 0; i < n; i++) {
String name = scanner.next();
int score = scanner.nextInt();
players[i] = new Player(name, score);
}
scanner.close();
// Use custom comparator to sort
Arrays.sort(players, new Checker());
// Print sorted result
for (Player p : players) {
System.out.println(p.name + " " + p.score);
}
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Comparator
You are viewing a single comment's thread. Return to all comments →
import java.util.*;
// Player class class Player { String name; int score;
}
// Checker class that implements Comparator class Checker implements Comparator { public int compare(Player a, Player b) { // First sort by descending score if (a.score != b.score) { return b.score - a.score; // higher score comes first } // If scores are equal, sort alphabetically by name return a.name.compareTo(b.name); } }
public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt();
}