Java - Non-lexicographical reverse order with Integers in max heap

Viewed 112

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()));
1 Answers

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.

Related