We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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());
}
}
}
}`
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Priority Queue
You are viewing a single comment's thread. Return to all comments →
`class Student{ private int id; private String name; private double 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(); } } } );
}`
`public class Solution {
}`