Java Priority Queue

  • + 0 comments

    My solution with java 8

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    /*
     * Create the Student and Priorities classes here.
     */
    import java.util.*;
    class Student {
        public int id;
        public String name;
        public 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 StudentComparator implements Comparator<Student>{
    
        @Override
        public int compare(Student s1, Student s2) {
    
            if(s1.cgpa == s2.cgpa){
                return s1.name.compareTo(s2.name);
            } else if (s1.cgpa == s2.cgpa && s1.name == s2.name){
                if(s1.id > s2.id)
                    return 1;
                else
                    return -1;
            } else if(s1.cgpa < s2.cgpa){
                return 1;
            } else if(s1.cgpa > s2.cgpa){
                return -1;
            } else {
                return 0;
            }
        }
    }
    class Priorities{
        public PriorityQueue<Student> q = new PriorityQueue<>(new StudentComparator());
        List<Student> student2List = new ArrayList<>();
    
        public List<Student> getStudents(List<String> events){
            for(String st : events){
    
                String[] parts = st.split(" ");
    
                if(parts[0].equals("ENTER")) {
                    q.add(new Student(Integer.parseInt(parts[3]), parts[1], Double.parseDouble(parts[2])));
    
                } else if (parts[0].equals("SERVED")){
                    q.poll();
                }
            }
    
            while(!q.isEmpty()){
                student2List.add(q.poll());
            }
    
            return student2List;
        }
    }
    
    
    public class Solution {
        private final static Scanner scan = new Scanner(System.in);
        private final static Priorities priorities = new Priorities();
        
        public static void main(String[] args) {
            int totalEvents = Integer.parseInt(scan.nextLine());    
            List<String> events = new ArrayList<>();
            
            while (totalEvents-- != 0) {
                String event = scan.nextLine();
                events.add(event);
            }
            
            List<Student> students = priorities.getStudents(events);
            
            if (students.isEmpty()) {
                System.out.println("EMPTY");
            } else {
                for (Student st: students) {
                    System.out.println(st.getName());
                }
            }
        }
    }