HackerRank Java- Comparator




Given an array of n Player objects, write a comparator that sorts them in order of decreasing score; if 2 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) method.



  1. import java.util.*;
  2. // Write your Checker class here
  3. class Checker implements Comparator<Player> {
  4. @Override
  5. public int compare(Player p1, Player p2) {
  6. if (p1.score == p2.score) {
  7. return p1.name.compareTo(p2.name);
  8. } else {
  9. return p2.score - p1.score;
  10. }
  11. }
  12. }
  13. class Player{
  14. String name;
  15. int score;
  16. Player(String name, int score){
  17. this.name = name;
  18. this.score = score;
  19. }
  20. }
  21. class Solution {
  22. public static void main(String[] args) {
  23. Scanner scan = new Scanner(System.in);
  24. int n = scan.nextInt();
  25. Player[] player = new Player[n];
  26. Checker checker = new Checker();
  27. for(int i = 0; i < n; i++){
  28. player[i] = new Player(scan.next(), scan.nextInt());
  29. }
  30. scan.close();
  31. Arrays.sort(player, checker);
  32. for(int i = 0; i < player.length; i++){
  33. System.out.printf("%s %s\n", player[i].name, player[i].score);
  34. }
  35. }
  36. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube