Near the Norbulingka Institute, Dharamshala, India
By
— 3 min read

Difference between sorted, sortWith and sortBy in Scala

Understand which sort method to use in what situation.

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:

1 personList.sortBy(_.age)

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:

1 personList.sortWith{(leftE,rightE) =>
2      leftE.age > rightE.age
3 }

Or, more simply:

1 personList.sortWith(_.age > _.age)

A full example

 1 // Sequence of numbers
 2 val xs = Seq(1, 5, 3, 4, 6, 2)
 3 
 4 // Sort using Natural ordering as defined for Integers in Scala Library
 5 xs.sorted //1,2,3,4,5,6
 6 
 7 // Sort 'with' a comparator function
 8 xs.sortWith(_<_) //1,2,3,4,5,6
 9 xs.sortWith(_>_) //6,5,4,3,2,1
10 xs.sortWith((left,right) => left > right) //6,5,4,3,2,1
11 
12 // Create a Person class
13 case class Person(val name:String, val age:Int)
14 
15 // Define a list of Persons
16 val ps = Seq(Person("John", 32), Person("Bruce", 24), Person("Cindy", 33), Person("Sandra", 18))
17 
18 // Sort People by increasing Age (natural ordering of Int will kick in)
19 ps.sortBy(_.age) //List(Person(Sandra,18), Person(Bruce,24), Person(John,32), Person(Cindy,33))
20 
21 // Sort People by decreasing Age, using a comparator function
22 ps.sortWith(_.age > _.age) //List(Person(Cindy,33), Person(John,32), Person(Bruce,24), Person(Sandra,18))