Reputation: 931
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
.
Upvotes: 23
Views: 25007
Reputation: 445
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}" )
Upvotes: 6
Reputation: 7001
MaxBy converts the values to a comparable type, and compares by the computed value
MaxWith compares the items with each other and sorts them by the return value of the comparator.
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 }
The same code with maxWith would look like this:
val maxWith = myMap.maxWith(Comparator({a, b -> a.value.compareTo(b.value)}))
Upvotes: 40