问题
I have a class Person
which has two attributes Name(String
) and Weight(Integer
).
I want to store elements in PriorityQueue according to their weight in descending order, i.e. higher the weight the top the element is in the queue.
I have tried this so far:
PriorityQueue<Person> personPriorityQueue = new PriorityQueue<Person>((a,b)-> Integer.compare(a.getWeight(), b.getWeight()));
personPriorityQueue.add(new Person(40,"N1"));
personPriorityQueue.add(new Person(60,"N2"));
personPriorityQueue.add(new Person(50,"N3"));
personPriorityQueue.forEach(s-> System.out.println(s.getName()));
Output I am getting is :
N1
N2
N3
I should get:
N2
N3
N1
回答1:
If you look at the documentation comment for the PriorityQueue.iterator
method it says:
Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.
The forEach
statement uses an iterator underneath, distorting the order of the elements retrieved from the PriorityQueue
. You have to use the poll
method on the queue to solve the issue. The poll
method removes the element from the head of the queue. Apart from that you have to fix the comparator to reverse the order since you need elements to be sorted in descending order. Here's the code.
Queue<Person> personPriorityQueue = new PriorityQueue<>(
Comparator.comparingInt(Person::getWeight).reversed());
while(!personPriorityQueue.isEmpty())
System.out.println(personPriorityQueue.poll().getName());
来源:https://stackoverflow.com/questions/59608220/priorityqueue-returning-elements-in-wrong-order