Java Priority Queue

  • + 0 comments

    Java 15 solution

    import java.io.*;
    import java.util.*;
    
    class Student{
        
         private int id;
         private String name;
         private double cgpa;
         
         Student(int id, String name, double cgpa){
            this.id = id;
            this.name = name;
            this.cgpa = cgpa;
         }
         
         int getID(){
            return this.id;
         }
         
         String getName(){
            return this.name;
         }
         
         double getCgpa(){
            return this.cgpa;
         }
    }
    
    class StudentComparator implements Comparator<Student>{
        
        public int compare(Student s1, Student s2){
            if(s1.getCgpa() < s2.getCgpa()) return 1;
            else if( s1.getCgpa() > s2.getCgpa()) return -1;
            else{
                return s1.getName().compareTo(s2.getName());
            }
        }
    }
    
    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 sc = new Scanner(System.in);
            int n = sc.nextInt();
            sc.nextLine();
            PriorityQueue<Student> pq = new PriorityQueue<Student>(n+1, new StudentComparator());
                    
            for(int i=0;i<n;i++){
                String str = sc.nextLine();
                String operation = str.split(" ")[0];
                if(operation.equals("ENTER")){
                    String name = str.split(" ")[1];
                    double cgpa = Double.parseDouble(str.split(" ")[2]);
                    int id = Integer.parseInt(str.split(" ")[3]);
                    pq.add(new Student(id,name,cgpa));   
                }
                else if(operation.equals("SERVED")){
                    pq.poll();
                }
            }
            
                List<Student> result = new ArrayList<>();
                while (!pq.isEmpty()) {
                    result.add(pq.poll());
                }
                    
                if (result.isEmpty()) {
                    System.out.println("EMPTY");
                } else {
                        for (Student st: result) {
                                System.out.println(st.getName());
                }
                
            }
    
        }
    }