FROM: http://www.iteblog.com/archives/1171?utm_source=tuicool
下面是一系列对Scala中的Lists、Array进行排序的例子,数据结构的定义如下:
02 |
val s = List( "a", "d", "F", "B", "e") |
03 |
val n = List(3, 7, 2, 1, 5) |
利用Scala内置的sorted方法进行排序
2 |
res0: List = List(B, F, a, d, e) |
5 |
res1: List[Int] = List(1, 2, 3, 5, 7) |
为什么我们这里不对m也排序呢?这是因为map对象没有sorted方法!
大小写敏感搜索
我们可以用Scala中的sortWith来自定义我们的对大小写敏感的排序函数。代码如下:
02 |
def compfn1(e1: String, e2: String) = (e1 compareToIgnoreCase e2) < 0 |
05 |
def compfn2(e1: String, e2: String) = (e1.toLowerCase < e2.toLowerCase) |
08 |
res2: List = List(a, B, d, e, F) |
11 |
res3: List = List(a, B, d, e, F) |
14 |
s.sortWith(_.toLowerCase < _.toLowerCase) |
15 |
res4: List = List(a, B, d, e, F) |
如何对Map中的Key或Value进行排序
其实很简单代码如下:
02 |
m.toList.sorted foreach { |
04 |
println(key + " = " + value) |
15 |
m.toList sortBy ( _._2 ) foreach { |
17 |
println(key + " = " + value) |
对源数据排序
上面的排序并不对原始的数据产生影响,排序的结果被存储到别的变量中,如果你的元素类型是数组,那么你还可以对数组本身进行排序,如下:
1 |
scala> val a = Array(2,6,1,9,3,2,1,-23) |
2 |
a: Array[Int] = Array(2, 6, 1, 9, 3, 2, 1, -23) |
4 |
scala> scala.util.Sorting.quickSort(a) |
7 |
res24: String = -23,1,1,2,2,3,6,9 |
可以看到a数组内部的数据已经排好序了。
如果你对上面的n进行排序,发现会报出如下的错误:
1 |
scala> scala.util.Sorting.quickSort(n) |
2 |
<console>:14: error: overloaded method value quickSort with alternatives: |
3 |
(a: Array[Float])Unit <and> |
4 |
(a: Array[Int])Unit <and> |
5 |
[K](a: Array[K])(implicit evidence$1: scala.math.Ordering[K])Unit <and> |
7 |
cannot be applied to (List[Int]) |
8 |
scala.util.Sorting.quickSort(n) |
从上面的报错信息我们可以看出,只有Array才可以用scala.util.Sorting.quickSort方法。
在scala.util.Sorting下面还有个stableSort函数,它可以对所有Seq进行排序,返回的结果为Array。比如我们对上面的n进行排序:
1 |
scala> scala.util.Sorting.stableSort(n) |
2 |
res35: Array[Int] = Array(1, 2, 3, 5, 7) |
而对Array排序返回Unit
1 |
scala> val a = Array(2,6,1,9,3,2,1,-23) |
2 |
a: Array[Int] = Array(2, 6, 1, 9, 3, 2, 1, -23) |
4 |
scala> scala.util.Sorting.stableSort(a) |
7 |
res39: String = -23,1,1,2,2,3,6,9 |
从名字上我们也可以看出,stableSort是稳定排序。所以可以根据需要进行选择。
本博客文章除特别声明,全部都是原创!
尊重原创,转载请注明: 转载自过往记忆(http://www.iteblog.com/)
本文链接地址: 《如何对Scala中集合(Collections)进行排序》(http://www.iteblog.com/archives/1171)