I am using priority queue to sort the list of student on basis of cgpa which is a double value. If I am making it as integer than it is working fine or if I add a field name as string and sort on basis of string then also it works fine.
public class MainClass {
public static void main(String[] args) {
// comparator class to sort the student on basis of cgpa.
Comparator<Student> studentComparator = new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if (s1.getCgpa() < s2.getCgpa())
return 1;
else if (s1.getCgpa() > s2.getCgpa())
return -1;
else
return 0;
}
};
Scanner in = new Scanner(System.in);
int totalEvents = 8;
PriorityQueue<Student> studentList = new PriorityQueue<>(totalEvents, studentComparator);
// adding value in to priority queue by taking input from user in cmd
while(totalEvents>0) {
double cgpa = in.nextDouble();
Student student = new Student(cgpa);
studentList.add(student);
totalEvents--;
}
for (Student s : studentList) {
System.out.println(s.getCgpa());
}
}
}
Here is my model class.
class Student {
private double cgpa;
public Student(double cgpa) {
super();
this.cgpa = cgpa;
}
public double getCgpa() {
return cgpa;
}
}
Here is my input
3.75
3.8
3.7
3.85
3.9
3.6
3.95
3.95
and here is the output
3.95
3.95
3.9
3.85
3.8
3.6
3.7
3.75
I tried strictfp key word and tried to use Double wrapper class but still same issue.
Your code looks good, and even your code to iterate the priority queue is correct, but it is not giving you an ordered traversal. The reason for this is that the internal workings of PriorityQueue are such that an iterator cannot guarantee a specific order.
As the Javadoc for PriorityQueue discusses:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
Use Arrays.sort(studentList.toArray()):
Student[] students = Arrays.sort(studentList.toArray());
for (Student s : students) {
System.out.println(s.getCgpa());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With