In: Computer Science
package DS;
import java.util.*;
public class PriorityQueueDriver
{
public static void main(String[] pyari)
{
Scanner in = new Scanner(System.in);
// Creating Priority queue parameterized constructor
// with initial capacity is 8 and a StudentComparator
// instance as its parameters
PriorityQueue<MyStudent> pq = new
PriorityQueue<MyStudent>
(8, new MyStudentComparator());
// Creates a Student object using
// parameterized constructor
// and adds the student object to priority queue
pq.add(new MyStudent("Pyari", 99.98));
pq.add(new MyStudent("Sasmita", 87.62));
pq.add(new MyStudent("Ram", 66.22));
pq.add(new MyStudent("Manvi", 94.36));
pq.add(new MyStudent("Tnvi", 84.36));
// Printing names of students in priority order,poll()
// method is used to access the head element of queue
System.out.println("Students served in their " +
"priority order of total mark.");
// Loops till queue is not empty
while (!pq.isEmpty())
System.out.println(pq.poll().getName());
}// End of main method
}// End of driver class PriorityQueueDriver
// Defines a class MyStudentComparator implementing
// Comparator interface
class MyStudentComparator implements Comparator<MyStudent>
{
// Overriding compare() method of Comparator
// for descending order of total
public int compare(MyStudent firstStu, MyStudent secondStu)
{
// Checks if first student total mark is less than
// second student total mark then return 1
if (firstStu.getTotal() < secondStu.getTotal())
return 1;
// Otherwise checks if first student total mark
// is greater than second student total mark
// then return -1
else if (firstStu.getTotal() > secondStu.getTotal())
return -1;
// Otherwise both are equal return 0
return 0;
}// End of method
} // End of class MyStudentComparator
// Defines a class student to store student information
class MyStudent
{
// To stores name and total mark
private String name;
private double total;
// Parameterized student constructor to assign
// parameter values to instance variables
public MyStudent(String na, double tot)
{
name = na;
total = tot;
}// End of parameterized constructor
// Method to return name
public String getName()
{
return name;
}// End of method
// Method to return total
public double getTotal()
{
return total;
}// End of method
}// End of class Student
Sample Output:
Students served in their priority order of total mark.
Pyari
Manvi
Sasmita
Tnvi
Ram