Created
July 26, 2014 06:24
-
-
Save gsluthra/80555ed4af24bea244b5 to your computer and use it in GitHub Desktop.
Sorting lists in scala using sorted(), sortWith() and sortBy()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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