Get entry with max value from Map in Kotlin

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)}))

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}" )

Tags:

Kotlin