Scala比较器---Ordered与Ordering
1.Ordered 和 Ordering
Scala提供两个特质(trait)Ordered
与Ordering
用于比较。其中,Ordered混入(mix)Java的Comparable接口,而Ordering则混入Comparator接口。众所周知,在Java中
- 实现Comparable接口的类,其对象具有了可比较性;
- 实现comparator接口的类,则提供一个外部比较器,用于比较两个对象。
Ordered与Ordering的区别与之相类似:
- Ordered特质定义了相同类型间的比较方式,但这种内部比较方式是单一的;
- Ordering则是提供比较器模板,可以自定义多种比较方式。
2.Ordered
Ordered特质更像是rich版的Comparable接口,除了compare方法外,更丰富了比较操作(<, >, <=, >=):
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.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)))
参考文献: