I have a class that uses priority queue to display 5 strings in ascending order. I understand that to make it in descending order i can use the “collections.reverseOrder()” method. How use this method with the following code?
import java.util.*;
public class queue {
public static void main (String[] args) {
PriorityQueue<String> sQ = new PriorityQueue<String>();
sQ.add("theodore");
sQ.add("theo");
sQ.add("Shailee");
sQ.add("Deborah");
sQ.add("Fernando");
sQ.add("th");
while (sQ.size() > 0)
System.out.println(sQ.remove());
Collections.reverseOrder(); //I am stuck here...
}
}
Try something like this, before removing the elements in
sQ:Because you’re using the natural ordering of
String, it makes sense to just build anotherPriorityQueuepassing as a parameter a new comparator that compares strings but reversing the order (notice the-sign in front of the comparison).EDIT:
As has been pointed in the comments, this is an even simpler solution: