Hey I want to use custom comparator in priority qu...
# android
v
Hey I want to use custom comparator in priority queue in kotlin. I have data class Product.kt
Copy code
data class Product(val value: String? = null, val price: String? = null) {
    var priceInLong = price?.toLong()
}
I want to create a min heap where price value will be minimum. I am creating the object but it giving me some kind of error
Copy code
fun main() {
    var queue = PriorityQueue<Long> { p1: Product, p2: Product ->
        p1.priceInLong?.let {
            p2.priceInLong?.minus(it)
        }
    }

    val list = listOf(
        Product("1", "4.83"),
        Product("2", "4.53"),
        Product("3", "3.54"),
        Product("4", "3.66"),
        Product("5", "5.16")
    )
}
Error
Copy code
None of the following functions can be called with the arguments supplied.
<init>((MutableCollection<out TypeVariable(E)!>..Collection<TypeVariable(E)!>?))   where E = TypeVariable(E) for    constructor PriorityQueue<E : Any!>(c: (MutableCollection<out E!>..Collection<E!>?)) defined in java.util.PriorityQueue
<init>(Comparator<in TypeVariable(E)!>!)   where E = TypeVariable(E) for    constructor PriorityQueue<E : Any!>(comparator: Comparator<in E!>!) defined in java.util.PriorityQueue
<init>(PriorityQueue<out TypeVariable(E)!>!)   where E = TypeVariable(E) for    constructor PriorityQueue<E : Any!>(c: PriorityQueue<out E!>!) defined in java.util.PriorityQueue
<init>(SortedSet<out TypeVariable(E)!>!)   where E = TypeVariable(E) for    constructor PriorityQueue<E : Any!>(c: SortedSet<out E!>!) defined in java.util.PriorityQueue
<init>(Int)   where E = TypeVariable(E) for    constructor PriorityQueue<E : Any!>(initialCapacity: Int) defined in java.util.PriorityQueue
cNIbo.png
1. I want to solve this error and add value by price which is minimum comes first. 2. Is my above queue comparator logic is correct to use min heap?
a
Why are you using
PriorityQueue<Long>
, if you are putting in
Product
(presumably)? Are you sure comparators can return null? You likely need to handle null prices. I would also advise against using
?.let
, it makes it less readable when using it for control flow.
z
I'm more confused why your data class has nullable values. If value is null then you don't have a product. If price is bill you can use 0.00
v
Okk sure thanks everyone
m
In addition to what people already said above - in Kotlin, you can use
compareBy
to easily create a comparator (including multi field comparation). For example:
Copy code
val queue = PriorityQueue<Product>(compareBy { it.priceInLong })
queue += Product("1", "4.83")
// others...
3
v
Nice @Marcello Galhardo thanks a million
337 Views