从Kotlin的Map获取具有最大值的条目 [英] Get entry with max value from Map in Kotlin
问题描述
我无法理解如何从 Map 界面使用maxBy
和maxWith
方法.我有以下代码:
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 { ??? }
我想获取具有最大值的条目,但我不知道该如何传递给maxBy
或maxWith
.
I'd like to get the entry with max value but I don't know what to pass to maxBy
or maxWith
.
推荐答案
MaxBy
MaxBy将值转换为可比较的类型,并按计算出的值进行比较
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.
MaxBy通常更有意义,因为它通常更快(尽管使用YMMV),而且实现可能更简单,但是如果只能通过比较对项目进行排序,则可能需要使用maxWith.
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.
这将获得最高价值的条目:
This gets the highest value entry:
var maxBy = myMap.maxBy { it.value }
与maxWith相同的代码如下所示:
The same code with maxWith would look like this:
val maxWith = myMap.maxWith(Comparator({a, b -> a.value.compareTo(b.value)}))
这篇关于从Kotlin的Map获取具有最大值的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!