pmaurais pmaurais - 1 year ago 94
Scala Question

Getting the maximum key value pair in a Scala map by value

I am trying to pull the maximum value form a map along with its key. For example:

val map = Map('a' -> 100, 'b' -> 23, ... 'z' -> 56)

Where 100 is the largest value, how would I go about pulling ('a',100)? I essentially want to use Map.max but search by value rather than key.

0__ 0__
Answer Source

You can use maxBy with a function from the key-value pair to just the value:

val map = Map('a' -> 100, 'b' -> 23, 'z' -> 56)

map.maxBy(_._2)  // (a,100)

This is a short form for

map.maxBy { case (key, value) => value }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download