简体   繁体   English

按值获取Scala映射中的最大键值对

[英]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)? 如果100是最大值,我将如何拉('a',100)? I essentially want to use Map.max but search by value rather than key. 我基本上想要使用Map.max但是按值而不是键搜索。

You can use maxBy with a function from the key-value pair to just the value: 您可以将maxBy与键值对中的函数一起使用,只使用值:

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 }

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM