Get entry with max value from Map in Kotlin

2020-07-06 06:01发布

I cannot understand how to use maxBy and maxWith methods from Map interface. I have this code:

var myMap: Map<String, Int> = mutableMapOf()
// ...
var best = myMap.maxBy { ??? }

I'd like to get the entry with max value but I don't know what to pass to maxBy or maxWith.

标签: kotlin
2条回答
Explosion°爆炸
2楼-- · 2020-07-06 06:34

Create a class like below

 data class Student(val name: String, val age: Int)

Now goto Oncreate

 val public = listOf(Student("param",29),
            Student("nilesh", 19),
            Student("rahul", 13),
            Student("venkat", 12),
            Student("Ram", 22),
            Student("Sonam", 18))

Now for maxBy in Create

val maxAge=public.maxBy { p-> p.age }
    println(maxAge)
    println("Student Name: ${maxAge?.name}" )
    println("Student Age: ${maxAge?.age}" )

and for minBy in Create

val minAge = public.minBy { p->p.age }
    println(minAge)
    println("Student Name: ${minAge?.name}" )
    println("Student Age: ${minAge?.age}" )
查看更多
▲ chillily
3楼-- · 2020-07-06 06:44

MaxBy

MaxBy converts the values to a comparable type, and compares by the computed value

MaxWith

MaxWith compares the items with each other and sorts them by the return value of the comparator.

Which one to use

MaxBy makes more sense usually, because it is usually faster (although YMMV), and because implementations can be simpler, but if the items can only be sorted by comparing then maxWith may be needed.

How to use it

This gets the highest value entry:

var maxBy = myMap.maxBy { it.value }

The same code with maxWith would look like this:

val maxWith = myMap.maxWith(Comparator({a, b -> a.value.compareTo(b.value)}))
查看更多
登录 后发表回答