Scala collections provide you three options for sorting: sorted()
, sortWith()
and sortBy()
. Here is a simplified explanation:
sorted
Will sort the list using the natural ordering (based on the implicit Ordering passed)
sortBy (an attribute)
Sort by a given attribute using the attribute’s type.
e.g. given a list of Person
objects, if you want to sort them in ascending order of their age
(which is an Int
), you could simply say:
|
|
sortWith (a function)
Takes a comparator function. Useful when you want to specify a custom sorting logic. e.g. if you want to sort by age descending, you could write this as:
|
|
Or, more simply:
|
|
A full example
|
|