scala基础知识--Ordering

trait Ordering[T] extends Comparator[T] with PartialOrdering[T] with Serializable
英文解释
Ordering is a trait whose instances each represent a strategy for sorting instances of a type.

Ordering’s companion object defines many implicit objects to deal with subtypes of AnyVal (e.g. Int, Double), String, and others.

To sort instances by one or more member variables, you can take advantage of these built-in orderings using Ordering.by and Ordering.on:

具体来说,就是Ordering一般放在类似于Sorting、top这类的排序方法中用来设定排序顺序。好了,直接上代码

 import scala.util.Sorting

 val pairs = Array(("a", 5, 2), ("c", 3, 1), ("b", 1, 3))
 Sorting.quickSort(pairs)(Ordering.by[(String, Int, Int), Int](_._2))

意思是以Array里每一个元组的第三个元素为排序依据(元组下标从1开始),_._2就是取第二个元素
输出:

scala> pairs
res1: Array[(String, Int, Int)] = Array((b,1,3), (c,3,1), (a,5,2))

同理:

scala> Sorting.quickSort(pairs)(Ordering.by[(String, Int, Int), Int](_._3))
scala> pairs
res6: Array[(String, Int, Int)] = Array((c,3,1), (a,5,2), (b,1,3))

还有《Spark机器学习》p74

val sortedSims = sims.top(K)(Ordering.by[(Int, Double), Double]{case
      (id, similarity) => similarity})

猜你喜欢

转载自blog.csdn.net/qq_30982323/article/details/78275658
今日推荐