Kotlin | Priority Queue of type max heap with custom comparator

Viewed 3202

I want to create a priority queue (max heap) for objects of the following class

data class Tuple(val column: Column, var count: Int)

where Column is

data class Column(val name: String, val dataType: String)

I wrote the following code to instantiate a priority queue for the above class objects with custom comparator like so:

val compareByCount: Comparator<Tuple> = compareByDescending { it.count }
val pq = PriorityQueue<Tuple>(compareByCount) 

When I populate the PriorityQueue and perform pq.peek() it returns the Tuple object with the lowest count. Why is it so? Even though I provided a comparator that checks according to descending order.

1 Answers

From my understanding compareByDescending should order the elements with the biggest count and the beginning of the heap.

But since this is not giving you the expected result maybe you can try this out:

val compareByCount = Comparator<Tuple> {t1, t2 -> t1.count - t2.count}

Or ever simpler, without a custom comparator:

val pq = PriorityQueue {t1: Tuple, t2 : Tuple -> t1.count - t2.count}

This will add the elements to the heap in the oposite order as compareByDescending

Related