Collections.reverseOrder() comparator does lexicographical sorting when used with a max heap toArray function.
Example: 4, 35, 41 would print as 41, 4, 35.
What I want is for it to print as 41, 35, 4
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
maxHeap.add(4);
//Prints [4]
System.out.println("MaxHeap:"+ Arrays.toString(maxHeap.toArray()));
maxHeap.add(35);
//Prints [35, 4]
System.out.println("MaxHeap:"+ Arrays.toString(maxHeap.toArray()));
maxHeap.add(41);
//Prints [41, 4, 35]
System.out.println("MaxHeap:"+ Arrays.toString(maxHeap.toArray()));
The default comparator of an Integer is not lexicographical.
The problem is that the internal array used by an PriorityQueue (which is what toArray()
returns) is not sorted.
To get the elements in the sorted order you need to call the poll()
method in the PriorityQueue until there are no more elements. This how the PriorityQueue functions by definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With