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

后端 未结 2 892
孤街浪徒
孤街浪徒 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:27

    A slight modification in case the max value you are looking for is present more than once in the map:

    // Find the entries with the max value in the map
    val maxValue = map.maxBy(item => item._2)
    
    // Filter the map and retain the entries with the max value
    map.filter(item => item._2 == maxValue._2)
    

提交回复
热议问题