<\/span><\/h2>\n\n\n\nComparators are used to compare two objects. In this challenge, you’ll create a comparator and use it to sort an array.
The Player class is provided for you in your editor. It has 2 <\/strong>fields: a name <\/em><\/strong>String and a score <\/em><\/strong>integer.
Given an array of n <\/strong>Player objects, write a comparator that sorts them in order of decreasing score; if 2 <\/strong>or more players have the same score, sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2)<\/code> method.<\/p>\n\n\n\n<\/span>Input Format<\/strong><\/span><\/h2>\n\n\n\nInput from stdin is handled by the locked stub code in the Solution class.<\/p>\n\n\n\n
The first line contains an integer, n<\/em><\/strong>, denoting the number of players.
Each of the n <\/em><\/strong>subsequent lines contains a player’s name <\/em><\/strong>and score<\/em><\/strong>, respectively.<\/p>\n\n\n\n<\/span>Constraint<\/strong><\/span><\/h4>\n\n\n\n- 0 <= score <= 1000<\/em><\/strong><\/li>
- 2 <\/strong>players can have the same name.<\/li>
- Player names consist of lowercase English letters.<\/li><\/ul>\n\n\n\n
<\/span>Output Format<\/strong><\/span><\/h2>\n\n\n\nYou are not responsible for printing any output to stdout. The locked stub code in Solution will create a Checker object, use it to sort the Player array, and print each sorted element.<\/p>\n\n\n\n
<\/span>Sample Input<\/strong><\/span><\/h4>\n\n\n\n 5\n amy 100\n david 100\n heraldo 50\n aakansha 75\n aleksa 150<\/code><\/pre>\n\n\n\n<\/span>Sample Output<\/strong><\/span><\/h4>\n\n\n\n aleksa 150\n amy 100\n david 100\n aakansha 75\n heraldo 50<\/code><\/pre>\n\n\n\n<\/span>Solution –<\/strong> Java Comparator<\/strong><\/span><\/h2>\n\n\n\nimport java.util.*;\n\n\/\/ Write your Checker class here\nclass Checker implements Comparator {\n public int compare(Object o1, Object o2) {\n Player p1 = (Player) o1;\n Player p2 = (Player) o2;\n if (p2.score - p1.score == 0) return p1.name.compareTo(p2.name);\n return p2.score - p1.score;\n }\n}\n\nclass Player{\n String name;\n int score;\n \n Player(String name, int score){\n this.name = name;\n this.score = score;\n }\n}\n\nclass Solution {\n\n public static void main(String[] args) {\n Scanner scan = new Scanner(System.in);\n int n = scan.nextInt();\n\n Player[] player = new Player[n];\n Checker checker = new Checker();\n \n for(int i = 0; i < n; i++){\n player[i] = new Player(scan.next(), scan.nextInt());\n }\n scan.close();\n \n Arrays.sort(player, checker);\n for(int i = 0; i < player.length; i++){\n System.out.printf(\"%s %s\\n\", player[i].name, player[i].score);\n }\n }\n}<\/pre>\n\n\n\n