33
你将如何按值排序scala.collection.Map [java.lang.String,Int](如此在Int中)?什么是简短和优雅的方式来做到这一点?如何按照其值排序scala.collection.Map [java.lang.String,Int]?
你将如何按值排序scala.collection.Map [java.lang.String,Int](如此在Int中)?什么是简短和优雅的方式来做到这一点?如何按照其值排序scala.collection.Map [java.lang.String,Int]?
根据预期的输出集合类型是什么(SortedMap
s的上的按键排序),你可以使用这样的事情:
Map("foo"->3, "raise"->1, "the"->2, "bar"->4).toList sortBy {_._2}
结果将是排序的键/值对的列表值:
List[(java.lang.String, Int)] = List((raise,1), (the,2), (foo,3), (bar,4))
没有保留原来的顺序,ListMap
,如果你申请这个,你必须再次地图一个地图类型:
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))
(斯卡拉2.8)
+10,认真有用,列表地图保存后序列表排序 – virtualeyes 2012-06-30 03:06:37
约递减顺序是什么? – vefthym 2017-03-17 08:08:06
@vefthym'Map(“foo” - > 3,“raise” - > 1,“the” - > 2,“bar” - > 4).toList sortWith {_._ 2> _._ 2} – 2017-07-20 14:13:01