Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get entry with max value from Map in Kotlin

Tags:

kotlin

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.

like image 245
Mpac Avatar asked Oct 31 '17 00:10

Mpac


People also ask

How do you get max value in Kotlin?

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.

How do you access map values in Kotlin?

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 .


2 Answers

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)}))
like image 149
jrtapsell Avatar answered Oct 04 '22 08:10

jrtapsell


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}" )
like image 28
Paramatma Sharan Avatar answered Oct 04 '22 09:10

Paramatma Sharan