Getting the maximum pair of key values ​​in a Scala map by value

I am trying to extract the maximum value from the card along with its key. For instance:

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

Where 100 is the highest value, how would I draw ('a', 100)? I essentially want to use Map.max, but search by value, not by key.

+6
source share
1 answer

You can use maxBy with a function from a key-value pair to a 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 } 
+16
source

All Articles