【转】如何对Scala中集合(Collections)进行排序

 

FROM: http://www.iteblog.com/archives/1171?utm_source=tuicool

 

下面是一系列对Scala中的Lists、Array进行排序的例子,数据结构的定义如下:

01 // data structures working with
02 val s = List( "a", "d", "F", "B", "e")
03 val n = List(3, 7, 2, 1, 5)
04 val m = Map(
05     -2 -> 5,
06     2 -> 6,
07     5 -> 9,
08     1 -> 2,
09     0 -> -16,
10     -1 -> -4
11 )

  利用Scala内置的sorted方法进行排序

1 s.sorted
2 res0: List = List(B, F, a, d, e)
3  
4 n.sorted
5 res1: List[Int] = List(1, 2, 3, 5, 7)

  为什么我们这里不对m也排序呢?这是因为map对象没有sorted方法!

大小写敏感搜索

  我们可以用Scala中的sortWith来自定义我们的对大小写敏感的排序函数。代码如下:

01 /* sort alphabetical and ignoring case */
02 def compfn1(e1: String, e2: String) = (e1 compareToIgnoreCase e2) < 0
03  
04 /* sort alphabetical and ignoring case: alternate */
05 def compfn2(e1: String, e2: String) = (e1.toLowerCase < e2.toLowerCase)
06  
07 s.sortWith(compfn1)
08 res2: List = List(a, B, d, e, F)
09  
10 s.sortWith(compfn2)
11 res3: List = List(a, B, d, e, F)
12  
13 /* Or you can do so using anonymous function (Thanks Rahul) */
14 s.sortWith(_.toLowerCase < _.toLowerCase)
15 res4: List = List(a, B, d, e, F)

如何对Map中的Key或Value进行排序

  其实很简单代码如下:

01 // sort by key can use sorted
02 m.toList.sorted foreach {
03     case (key, value) =>
04         println(key + " = " + value)
05 }
06  
07 -2 = 5
08 -1 = -4
09 0 = -16
10 1 = 2
11 2 = 6
12 5 = 9
13  
14 // sort by value
15 m.toList sortBy ( _._2 ) foreach {
16     case (key, value) =>
17         println(key + " = " + value)
18 }
19  
20 0 = -16
21 -1 = -4
22 1 = 2
23 -2 = 5
24 2 = 6
25 5 = 9

对源数据排序

  上面的排序并不对原始的数据产生影响,排序的结果被存储到别的变量中,如果你的元素类型是数组,那么你还可以对数组本身进行排序,如下:

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)
3  
4 scala> scala.util.Sorting.quickSort(a)
5  
6 scala> a.mkString(",")
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>
6   (a: Array[Double])Unit
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)
3  
4 scala> scala.util.Sorting.stableSort(a)
5  
6 scala> a.mkString(",")
7 res39: String = -23,1,1,2,2,3,6,9

  从名字上我们也可以看出,stableSort是稳定排序。所以可以根据需要进行选择。

本博客文章除特别声明,全部都是原创!
尊重原创,转载请注明: 转载自过往记忆(http://www.iteblog.com/)
本文链接地址: 《如何对Scala中集合(Collections)进行排序》(http://www.iteblog.com/archives/1171)

posted @ 2015-07-06 10:41  MERRU  阅读(805)  评论(0)    收藏  举报