Scala比較器---Ordered與Ordering

1.Ordered 和 Ordering

Scala提供兩個特質(trait)OrderedOrdering用於比較。其中,Ordered混入(mix)Java的Comparable接口,而Ordering則混入Comparator接口。衆所周知,在Java中html

  • 實現Comparable接口的類,其對象具備了可比較性;
  • 實現comparator接口的類,則提供一個外部比較器,用於比較兩個對象。

Ordered與Ordering的區別與之相相似:python

  • Ordered特質定義了相同類型間的比較方式,但這種內部比較方式是單一的;
  • Ordering則是提供比較器模板,能夠自定義多種比較方式。

 

2.Ordered

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)
}

  

3.Ordering 

Ordering,內置函數Ordering.byOrdering.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

【1】Scala比較器:Ordered與Ordering - Jason的專欄 - CSDN博客this

【2】Scala Standard Library API (Scaladoc) 2.10.5 - Ordered - Scala Standard Library API (Scaladoc) 2.10.5 - scala.math.Ordered.net

相關文章
相關標籤/搜索