PriorityQueue returning elements in wrong order [duplicate]

拟墨画扇 提交于 2020-01-14 03:39:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!