Scala提供兩個特質(trait)Ordered
與Ordering
用於比較。其中,Ordered混入(mix)Java的Comparable接口,而Ordering則混入Comparator接口。衆所周知,在Java中html
Ordered與Ordering的區別與之相相似:python
Ordered特質更像是rich版的Comparable接口,除了compare方法外,更豐富了比較操做(<, >, <=, >=):api
trait Ordered[T] extends Comparable[T] { def compare(that: A): Int def < (that: A): Boolean = (this compare that) < 0 def > (that: A): Boolean = (this compare that) > 0 def <= (that: A): Boolean = (this compare that) <= 0 def >= (that: A): Boolean = (this compare that) >= 0 def compareTo(that: A): Int = compare(that) }
Ordering,內置函數Ordering.by
與Ordering.on
進行自定義排序:函數
import scala.util.Sorting val pairs = Array(("a", 5, 2), ("c", 3, 1), ("b", 1, 3)) // sort by 2nd element Sorting.quickSort(pairs)(Ordering.by[(String, Int, Int), Int](_._2)) // sort by the 3rd element, then 1st Sorting.quickSort(pairs)(Ordering[(Int, String)].on(x => (x._3, x._1)))
參考文獻:ui