This question already has an answer here:
- Change priorityQueue to max priorityqueue 14 answers
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 :/
Use Java's Collections.reverseOrder()
comparator.
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);
}
}
来源:https://stackoverflow.com/questions/3705881/changing-java-priorityqueue-to-a-max-pq