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
.
Create a class like below
Now goto Oncreate
Now for maxBy in Create
and for minBy in Create
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:
The same code with maxWith would look like this: