Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between sorted and sortBy

According to doc for List

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.

When would you use one and when would you use the other? Does one cover a scenario the other does not?

like image 650
More Than Five Avatar asked Jan 13 '23 10:01

More Than Five


1 Answers

For sortBy you can supply custom function that produces elements used for sorting (e.g. sort by the length string) whereas for sorted you cant:

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)

as you can see, last three lines are identical in their result

like image 197
om-nom-nom Avatar answered Jan 22 '23 22:01

om-nom-nom