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

后端 未结 2 893
孤街浪徒
孤街浪徒 2021-01-01 23:51

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)

2条回答
  •  梦谈多话
    2021-01-02 00:25

    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 }
    

提交回复
热议问题