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
.
You can use max() , if you want to use the default comparison (as in your case with int s), or maxBy , if you want to use a custom selector (i.e., algorithm) to compare values. Save this answer.
For retrieving a value from a map, you must provide its key as an argument of the get() function. The shorthand [key] syntax is also supported. If the given key is not found, it returns null .
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)}))
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}" )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With