如何按值对 scala.collection.Map[java.lang.String, Int] 进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2972871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:12:14  来源:igfitidea点击:

how to sort a scala.collection.Map[java.lang.String, Int] by its values?

sortingscalascala-collections

提问by Jan Willem Tulp

How would you sort a scala.collection.Map[java.lang.String, Int] by its values (so on the Int)? What is a short and elegant way to do that?

你将如何通过它的值(在 Int 上)对 scala.collection.Map[java.lang.String, Int] 进行排序?什么是一种简短而优雅的方式来做到这一点?

回答by mkneissl

Depending on what the expected output collection type is (SortedMaps are sorted on the keys), you could use something like this:

根据预期的输出集合类型(SortedMaps 按键排序),您可以使用以下内容:

Map("foo"->3, "raise"->1, "the"->2, "bar"->4).toList sortBy {_._2}

Result would be the list of key/value pairs sorted by the value:

结果将是按值排序的键/值对列表:

List[(java.lang.String, Int)] = List((raise,1), (the,2), (foo,3), (bar,4))

There is a Map type that retains the original order, ListMap, if you apply this, you have a map again:

有一个 Map 类型保留了原来的顺序ListMap,如果你应用这个,你又得到了一个地图:

import collection.immutable.ListMap                                          
ListMap(Map("foo"->3, "raise"->1, "the"->2, "bar"->4).toList.sortBy{_._2}:_*)

Then you have:

那么你有:

scala.collection.immutable.ListMap[java.lang.String,Int] = Map((raise,1), (the,2), (foo,3), (bar,4))

(Scala 2.8)

(斯卡拉 2.8)