Changing Java PriorityQueue to a Max PQ [duplicate]

旧巷老猫 提交于 2019-12-03 00:13:22
Suman Chitturi

Use Java's Collections.reverseOrder() comparator.

Java Reference

Here is a code snippet using Collections.reverseOrder()-

    PriorityQueue<Integer> maxPQ = new PriorityQueue<Integer>(20,Collections.reverseOrder());

You also need to provide the initial capacity of the Priority Queue (20 here) along with the Comparator.

Not sure what you mean by elegant but when I want a PQ implemented like a MaxHeap (used in Dijkstra's) I just use an inline comparator constructor.

PriorityQueue<Integer> PQ= new PriorityQueue<Integer>(20, new Comparator<Integer>(){
            public int compare(Integer o1, Integer o2){
                return o2 - o1;
            }
        });

It's simple enough for anytime I'm looking for something simple and only want to use the Comparator once.

If you have an existing comparator you could create a generic inversing comparator.

public class InverseComparator<T> implements Comparator<T> {
    private final Comparator<T> delegate;

    public InverseComparator(Comparator<T> delegate) {
        this.delegate = delegate;
    }

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