文章標題: 《如何對Scala中集合(Collections)進行排序》
本文鏈接: http://www.iteblog.com/archives/1171
下面是一系列對
Scala
中的Lists艺沼、Array進行排序的例子,數(shù)據(jù)結(jié)構(gòu)的定義如下:
// data structures working with
val s = List( "a", "d", "F", "B", "e")
val n = List(3, 7, 2, 1, 5)
val m = Map(
-2 -> 5,
2 -> 6,
5 -> 9,
1 -> 2,
0 -> -16,
-1 -> -4
)
利用 Scala 內(nèi)置的sorted方法進行排序
s.sorted
res0: List = List(B, F, a, d, e)
n.sorted
res1: List[Int] = List(1, 2, 3, 5, 7)
為什么我們這里不對m也排序呢调鲸?這是因為map對象沒有sorted方法挽荡!
大小寫敏感搜索
我們可以用 Scala 中的sortWith來自定義我們的對大小寫敏感的排序函數(shù)藐石。代碼如下:
/* sort alphabetical and ignoring case */
def compfn1(e1: String, e2: String) = (e1 compareToIgnoreCase e2) < 0
/* sort alphabetical and ignoring case: alternate */
def compfn2(e1: String, e2: String) = (e1.toLowerCase < e2.toLowerCase)
s.sortWith(compfn1)
res2: List = List(a, B, d, e, F)
s.sortWith(compfn2)
res3: List = List(a, B, d, e, F)
/* Or you can do so using anonymous function (Thanks Rahul) */
s.sortWith(_.toLowerCase < _.toLowerCase)
res4: List = List(a, B, d, e, F)
如何對Map中的Key或Value進行排序
// sort by key can use sorted
m.toList.sorted foreach {
case (key, value) =>
println(key + " = " + value)
}
-2 = 5
-1 = -4
0 = -16
1 = 2
2 = 6
5 = 9
// sort by value
m.toList sortBy ( _._2 ) foreach {
case (key, value) =>
println(key + " = " + value)
}
0 = -16
-1 = -4
1 = 2
-2 = 5
2 = 6
5 = 9
對源數(shù)據(jù)排序
上面的排序并不對原始的數(shù)據(jù)產(chǎn)生影響于微,排序的結(jié)果被存儲到別的變量中,如果你的元素類型是數(shù)組株依,那么你還可以對數(shù)組本身進行排序延窜,如下:
scala> val a = Array(2,6,1,9,3,2,1,-23)
a: Array[Int] = Array(2, 6, 1, 9, 3, 2, 1, -23)
scala> scala.util.Sorting.quickSort(a)
scala> a.mkString(",")
res24: String = -23,1,1,2,2,3,6,9
可以看到a數(shù)組內(nèi)部的數(shù)據(jù)已經(jīng)排好序了恋腕。如果你對上面的n進行排序逆瑞,發(fā)現(xiàn)會報出如下的錯誤:
scala> scala.util.Sorting.quickSort(n)
<console>:14: error: overloaded method value quickSort with alternatives:
(a: Array[Float])Unit <and>
(a: Array[Int])Unit <and>
[K](a: Array[K])(implicit evidence$1: scala.math.Ordering[K])Unit <and>
(a: Array[Double])Unit
cannot be applied to (List[Int])
scala.util.Sorting.quickSort(n)
從上面的報錯信息我們可以看出,只有Array才可以用scala.util.Sorting.quickSort方法商源。在scala.util.Sorting下面還有個stableSort函數(shù),它可以對所有Seq進行排序,返回的結(jié)果為Array扫沼。比如我們對上面的n進行排序:
scala> scala.util.Sorting.stableSort(n)
res35: Array[Int] = Array(1, 2, 3, 5, 7)
而對Array排序返回Unit
scala> val a = Array(2,6,1,9,3,2,1,-23)
a: Array[Int] = Array(2, 6, 1, 9, 3, 2, 1, -23)
scala> scala.util.Sorting.stableSort(a)
scala> a.mkString(",")
res39: String = -23,1,1,2,2,3,6,9