Sort by

recency

|

282 Discussions

|

  • + 0 comments

    This is a great exercise for understanding how custom sorting works using comparators! Betinexchange247 Login

  • + 0 comments
    class Checker implements Comparator<Player>{
        @Override
        public int compare(Player o1, Player o2) {
            if (o1.score != o2.score)
                return Integer.compare(o2.score, o1.score);
            else 
                return o1.name.compareTo(o2.name);
        }
     }
    
  • + 0 comments

    import java.io.; import java.util.; import java.util.List;

    public class Solution {

    public static void main(String[] args) {
    
        var players = new ArrayList<Players>();
        Scanner sc = new Scanner(System.in);
    
        int nums = Integer.parseInt(sc.nextLine());
    
    
    
    
    
        while(nums > 0)
        {
            String[] input = sc.nextLine().trim().split("\\s+");
            players.add(new Players(input[0], Integer.parseInt(input[1])));
            nums--;
    
    
    
        }
    
        Collections.sort(players, (p1, p2) -> {
            int result = Integer.compare(((Players) p2).getScore(), ((Players) p1).getScore());
            if (result == 0)
            {
                return ((Players) p1).getName().compareTo(((Players) p2).getName());
            }
            return result;
        });
        for (Players p : players) {
            System.out.println(p);
        }
        sc.close();
    
    }
    

    }

    class Players {

    private String name;
    private int score;
    
    
    public Players(String name, int score)
    {
        this.name = name;
        this.score = score;
    }
    
    public void setName(String name)
    {this.name = name;}
    
    public String getName()
    {return this.name;}
    
    public void setScore(int score)
    {this.score = score;}
    
    public int getScore()
    {return this.score;}
    
    public String toString()
    {return this.name + " " + this.score;}
    

    }

  • + 0 comments
    class Checker implements Comparator<Player>{
        
        @Override
        public int compare(Player p1, Player p2) {
            
            if(p1.score==p2.score){
                return p1.name.compareTo(p2.name);
            } else if (p1.score< p2.score) {
                return 1;
            }else {
                return -1;
            }
        }
    }
    
  • + 0 comments

    This is a great exercise for learning how to implement comparators in Java! exchange play