I need a Max-Priority Queue data structure.
Looking in Java’s Priority Queue I noticed that it is a Min-Priority Queue.
From javadoc:
The head of this queue is the least element with respect to the
specified ordering
I saw that there is the option to provide a custom Comparator and looking at some posts some suggest to use one and do the reverse comparison to achieve the result of a Max Priority Queue.
This seems to me though a “ugly-hack” and perhaps not intuitive.
Is this the only way to have a Max-Priority Queue from the Java’s standard collection?
Is there a more appropriate object I am missing? (E.g. a while back I didn’t realize that Stack was replaced by a Deque…my bad)
AFAIK, yes, it’s the best way to have what you want. I really don’t see how it’s an ugly hack. There is no point of providing two different classes if just one is sufficient. If we followed your reasoning, we would have a MinTreeSet and a MaxTreeSet, a MinTreeMap and a MaxTreeMap, etc., all doining exactly the same thing. It’s a classical use of the strategy pattern.
Just use
Collections.reverseOrder()to get a comparator that compares in the reverse order of the natural ordering.