Getting all key value pairs having the maximum value from a Scala map

寵の児 提交于 2019-12-02 11:40:33

问题


I have seen a similar post here here which is giving a single key-value pair which has maximum value in the entire Map.

But I would like to get List of pairs which has maximum value(maximum value is same for many pairs).

Ex : Map(1 -> 7, 2 -> 1, 4 -> 7, 3 -> 2)

Expected Output : List(1 -> 7, 4 -> 7)

This (Map(1 -> 7, 2 -> 1, 4 -> 7, 3 -> 2).maxBy(x => x._2)) will give only first occurrence 1 -> 7


回答1:


Using map.filter(_._2 == map.values.max) will do the trick.




回答2:


val maxValue = map.values.max
map.filter(_._2 == maxValue).toList


来源:https://stackoverflow.com/questions/49792228/getting-all-key-value-pairs-having-the-maximum-value-from-a-scala-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!