Java Priority Queue

  • + 0 comments

    `class Student{ private int id; private String name; private double cgpa;

    public Student (int id, String name, double cgpa){
        this.id = id;
        this.name = name;
        this.cgpa = cgpa;
    }
    public int getID(){
        return id;
    }
    public String getName(){
        return name;
    }
    public double getCGPA(){
        return cgpa;
    }
    

    }`

    `class Priorities{ public List getStudents(List events){ PriorityQueue queue = new PriorityQueue<>( new Comparator() { public int compare(Student stu1, Student stu2){ if(stu1.getCGPA()!= stu2.getCGPA()){ return Double.compare(stu2.getCGPA(), stu1.getCGPA()); }else if (!stu1.getName().equals(stu2.getName())){ return stu1.getName().compareTo(stu2.getName()); }else { return stu1.getID() - stu2.getID(); } } } );

        for (String e : events){
            String[] part = e.split(" ");
            if(part[0].equals("ENTER")){
                String name = part[1];
                double cgpa = Double.parseDouble(part[2]);
                int id = Integer.parseInt(part[3]);
                queue.add(new Student(id, name, cgpa));
            }else if (part[0].equals("SERVED")){
                queue.poll();
            }
        }
    
        List<Student> result = new ArrayList<>();
        while (!queue.isEmpty()){
            result.add(queue.poll());
        }
        return result;
    }
    

    }`

    `public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner input = new Scanner(System.in);
        int n = Integer.parseInt(input.nextLine());
    
        List<String> events = new ArrayList<>();
        while (n-- > 0){
            events.add(input.nextLine());
        }
    
        Priorities priorities = new Priorities();
        List<Student> students = priorities.getStudents(events);
    
        if(students.isEmpty()){
            System.out.println("EMPTY");
        }else {
            for (Student s : students){
                System.out.println(s.getName());
            }
        }
    }
    

    }`