Skip to content

Instantly share code, notes, and snippets.

@gsluthra
Created July 26, 2014 06:24
Show Gist options
  • Save gsluthra/80555ed4af24bea244b5 to your computer and use it in GitHub Desktop.
Save gsluthra/80555ed4af24bea244b5 to your computer and use it in GitHub Desktop.
Sorting lists in scala using sorted(), sortWith() and sortBy()
// Sequence of numbers
val xs = Seq(1, 5, 3, 4, 6, 2)
// Sort using Natural ordering as defined for Integers in Scala Library
xs.sorted //1,2,3,4,5,6
// Sort 'with' a comparator function
xs.sortWith(_<_) //1,2,3,4,5,6
xs.sortWith(_>_) //6,5,4,3,2,1
xs.sortWith((left,right) => left > right) //6,5,4,3,2,1
// Create a Person class
case class Person(val name:String, val age:Int)
// Define a list of Persons
val ps = Seq(Person("John", 32), Person("Bruce", 24), Person("Cindy", 33), Person("Sandra", 18))
// Sort People by increasing Age (natural ordering of Int will kick in)
ps.sortBy(_.age) //List(Person(Sandra,18), Person(Bruce,24), Person(John,32), Person(Cindy,33))
// Sort People by decreasing Age, using a comparator function
ps.sortWith(_.age > _.age) //List(Person(Cindy,33), Person(John,32), Person(Bruce,24), Person(Sandra,18))
@gsluthra
Copy link
Author

sorted Sorts the elements using natural ordering (implicit Ordering)
sortBy Sorts by a given attribute (using the natural ordering of the attribute's type).
sortWith Sorts with a specified comparator function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment