2010-06-04 30 views

回答

55

根据预期的输出集合类型是什么(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)

+0

+10,认真有用,列表地图保存后序列表排序 – virtualeyes 2012-06-30 03:06:37

+0

约递减顺序是什么? – vefthym 2017-03-17 08:08:06

+0

@vefthym'Map(“foo” - > 3,“raise” - > 1,“the” - > 2,“bar” - > 4).t​​oList sortWith {_._ 2> _._ 2} – 2017-07-20 14:13:01