Changing Java PriorityQueue to a Max PQ

Chris picture Chris · Sep 14, 2010 · Viewed 30.7k times · Source

The Priority Queue implementation in the Java standard library appears to be a min Priority Queue which I found somewhat confusing. In order to turn it into a max one I created a custom comparator object.

Comparator<Integer> cmp = new Comparator<Integer>()
{
    public int compare( Integer x, Integer y )
    {
        return y - x;
    }
};

I was wondering if there was a more elegant solution. Essentially I wan't a generic priority queue that could be used to implement Dijkstras etc. I didn't even realise there would be ones which operated in reverse :/

Answer

pyrometer picture pyrometer · Oct 1, 2012

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.