Convert comparator to lambda to Kotlin

There is snipt code in my Kotlin code:

val dataMap = sensoryDataUsage.groupBy { it } .mapValues { it.value.count().toDouble()/count } .mapKeys { println(it.key); it.key.toDouble()/max } .toSortedMap(object : Comparator<Double> { override fun compare(p0: Double, p1: Double): Int { return (p1-p0).compareTo(0) } }) 

Everything went perfectly. However, the IDE continues to offer me to convert this Comparator object to lambda, and I did just that:

 val dataMap = sensoryDataUsage.groupBy { it } .mapValues { it.value.count().toDouble()/count } .mapKeys { println(it.key); it.key.toDouble()/max } .toSortedMap {x, y -> (yx).compareTo(0)} 

This job. However, it cannot be compiled:

 Error:(32, 14) Kotlin: Type inference failed: fun <K, V> Map<out K, V>.toSortedMap(comparator: Comparator<in K>): SortedMap<K, V> cannot be applied to receiver: Map<Double, Double> arguments: ((Double, Double) -> Int) 

Any ideas what went wrong? Thanks in advance.

+5
source share
3 answers

Try as follows:

 val dataMap = sensoryDataUsage.groupBy { it } .mapValues { it.value.count().toDouble()/count } .mapKeys { println(it.key); it.key.toDouble()/max } .toSortedMap(Comparator<Double> { p0, p1 -> (p1-p0).compareTo(0) }) 

You have many answers with working code, but I will try to explain why your code did not work. Take a look at this lambda:

 p0, p1 -> (p1-p0).compareTo(0) 

It will generate a method that returns the type specified inside the last called method, in our case, compareTo . In other words, this lambda will return an integer. But your code needs double, so you must specify the return type as Double . Now that you’ve got your reasons, feel free to use any suggested solutions that suit you best.

+6
source

your code should look like this:

 val dataMap = sensoryDataUsage.groupBy { it } .mapValues { it.value.count().toDouble()/count } .mapKeys { println(it.key); it.key.toDouble()/max } .toSortedMap(Comparator<Double>{x, y -> (yx).compareTo(0)}); 

OR you can remove the yx expression:

 val dataMap = sensoryDataUsage.groupBy { it } .mapValues { it.value.count().toDouble()/count } .mapKeys { println(it.key); it.key.toDouble()/max } .toSortedMap(Comparator<Double>{x, y -> y.compareTo(x)}); 

OR instead of compareByDescending :

 val dataMap = sensoryDataUsage.groupBy { it } .mapValues { it.value.count().toDouble()/count } .mapKeys { println(it.key); it.key.toDouble()/max } .toSortedMap(compareByDescending{ it }); 
+3
source

Replace

 .toSortedMap {x, y -> (yx).compareTo(0)} 

with

 .toSortedMap {x:Double, y:Double -> (yx).compareTo(0)} 
0
source

Source: https://habr.com/ru/post/1269157/


All Articles