Reverse natural order using collections.reverseOrder()

java

Solution

Try something like this, before removing the elements in `sQ`:

PriorityQueue<String> reversed =
    new PriorityQueue<String>(sQ.size(), new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return -o1.compareTo(o2);
    }
});
reversed.addAll(sQ); // now `reversed` contains the reversed priority queue

Because you're using the natural ordering of `String`, it makes sense to just build another `PriorityQueue` passing 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:

PriorityQueue<String> reversed =
    new PriorityQueue<String>(sQ.size(), Collections.reverseOrder());
reversed.addAll(sQ);

Problem

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... } } ```

Original source