Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Created March 9, 2017 11:12
Show Gist options
  • Select an option

  • Save JoolsF/437807f78056465421cf03ca37f99f05 to your computer and use it in GitHub Desktop.

Select an option

Save JoolsF/437807f78056465421cf03ca37f99f05 to your computer and use it in GitHub Desktop.
Sorting / sortBy examples
/********************
* sortBy Example 1
********************/
case class Person(name: String, age: Int)
val people = List(Person("Julian", 35), Person("David", 25), Person("Linda", 40))
//ascending
people.sortBy(_.age) //List(Person("David", 25), Person("Julian", 35), Person("Linda", 40))
//descending
people.sortBy(-_.age) //List(Person("Linda", 40), Person("Julian", 35), Person("David", 25))
/********************
* sortBy Example 2
********************/
// These ids all have a start char and an ending digit.
val ids = List("a5", "b0", "z0", "c9", "d9", "d0", "d5")
// Create a sort key. The second char is first and the first char second.
ids.sortBy((x: String) => (x.charAt(1), x.charAt(0))) // result = b0, d0, z0, a5, d5, c9, d9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment