Reputation: 10419
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?
Upvotes: 4
Views: 258
Reputation: 67878
You would use sorted
with an Ordering
if you have to consider multiple cases. Suppose we want to sort the following list having shortest strings at the beginning.
val xs = "aa" :: "b" :: "bb" :: "a" :: Nil
xs.sortBy(_.length)
> List[String] = List(b, a, aa, bb)
If we want to additionally sort them alphabetically, when they have the same length, we could use sorted
xs.sorted(math.Ordering[(Int, String)].on((x: String) => (x.length, x)))
> List[String] = List(a, b, aa, bb)
But then again, we could have used
xs.sortBy(x => (x.length, x))
> List[String] = List(a, b, aa, bb)
as well.
The idea is that you can supply Ordering
type classes for your own types and then a simple xs.sorted
with such an implicit Ordering
will work for the most common use cases.
Upvotes: 3
Reputation: 62835
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
Upvotes: 6
Reputation: 6308
As a complement to @om-nom-nom's answer, here is an example of typical usage of the two:
val xs = List(4, 2, 3, 1)
val ys = List((1, 1), (3, 2), (2, 3))
println(xs.sorted) // List(1, 2, 3, 4)
println(ys.sortBy(_._1)) // List((1,1), (2,3), (3,2))
Upvotes: 0