Jan*_*ulp 33 sorting scala scala-collections
你如何按其值(在Int上)对scala.collection.Map [java.lang.String,Int]进行排序?什么是简短而优雅的方式呢?
mkn*_*ssl 55
根据预期的输出集合类型(SortedMap按键排序),您可以使用以下内容:
Map("foo"->3, "raise"->1, "the"->2, "bar"->4).toList sortBy {_._2}
Run Code Online (Sandbox Code Playgroud)
结果将是按值排序的键/值对列表:
List[(java.lang.String, Int)] = List((raise,1), (the,2), (foo,3), (bar,4))
Run Code Online (Sandbox Code Playgroud)
有一种保留原始订单的地图类型ListMap,如果您应用此订单,则会再次显示地图:
import collection.immutable.ListMap
ListMap(Map("foo"->3, "raise"->1, "the"->2, "bar"->4).toList.sortBy{_._2}:_*)
Run Code Online (Sandbox Code Playgroud)
然后你有:
scala.collection.immutable.ListMap[java.lang.String,Int] = Map((raise,1), (the,2), (foo,3), (bar,4))
Run Code Online (Sandbox Code Playgroud)
(斯卡拉2.8)