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

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

问题描述:

如何将scala.collection.Map [java.lang.String,Int]按其值排序(在Int上也是如此)?简短而优雅的方法是什么?

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?

取决于期望的输出集合类型是什么(SortedMap在键上排序),您可以使用类似以下的东西:

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

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))

有一种地图类型保留了原始顺序,ListMap.如果应用此类型,则又有一张地图:

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

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

那么你有:

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

(Scala 2.8)

(Scala 2.8)