1. Scala map sorting
对这样一个map根据value的开始值排序:
"01" -> List(34,12,14,23),"11" -> List(22,11,34)
方法一 scala.collection.immutable.TreeMap
此方法经常用来sorted by key
val t = TreeMap("01"->List(34,12,14,23),"11"->List(22,11,34)) //会自动按key排列
//如:
var tm = TreeMap(3 -> 'x', 1 -> 'x', 4 -> 'x')
println(tm)
//output:
Map(1 -> x, 3 -> x, 4 -> x)
如果已经有一个map的话:
val m = Map("01"-> List(34,12,14,23),"11"->List(22,11,34))
val t = TreeMap(m.toSeq:_*)
方法二 转换为Seq or List then sort it
// by specifying an element for sorting
m.toSeq.sortBy(_._1) //sort by keys
m.toSeq.sortBy(_._2) //sort by values
// by providing a sort function
m.toSeq.sortWith(_._1 < _._1) // sort by comparing keys
TreeMap是sortedMap的红黑树实现(应该差不多吧)。