2010-06-04 19 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

相關問題