sorted和sortBy之间的区别

Mor*_*ive 3 collections performance scala list time-complexity

根据列表的文件

def  sorted[B >: A](implicit ord: math.Ordering[B]): List[A] 
Sorts this list according to an Ordering.


def sortBy[B](f: (A) ? B)(implicit ord: math.Ordering[B]): List[A]

Sorts this List according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.
Run Code Online (Sandbox Code Playgroud)

你何时会使用另一个?你何时会使用另一个?是否覆盖了另一个没有的情景?

om-*_*nom 6

对于sortBy,您可以提供自定义函数来生成用于排序的元素(例如,按长度字符串排序),而对于排序,您不能:

val xs = List("aa", "b")
// xs: List[String] = List(aa, b)
xs.sortBy{ str => str.length }
// List[String] = List(b, aa)

// now usual lexicographical sorting
xs.sorted
// List[String] = List(aa, b)
xs.sortBy(x => x)
// List[String] = List(aa, b)
xs.sortBy(identity)
// List[String] = List(aa, b)
Run Code Online (Sandbox Code Playgroud)

如您所见,最后三行的结果相同

  • @Debilski你是在作弊!;-) (2认同)