Scala Examples - Sorting Lists and other Collections in Scala

Last updated:

Lists (and other collections) are probably the most important things you'll deal with when programming with functional programming languages, and sorting is one of the most common operations on them. Here are some examples:

Using sorted


List("foo", "bar", "baz").sorted

Using sortBy to specify the order criteria

// (Int,String) pairs
val p1 = (5,"foo")
val p2 = (19,"bar")
val p3 = (12,"baz")
val p4 = (5,"quux")

val list = List(p1,p2,p3,p4)

list.sortBy( el => (el._1,el._2))) //use the first element then the second
//List((5,foo), (5,qux), (12,baz), (19,bar))

list.sortBy(_._2) //sort list using only the second element (the string)
//List((19,bar), (12,baz), (5,foo), (5,qux))

Totally custom ordering with orderWith

You provide a custom function (A,A) => Boolean(where Ais the list type) that takes two parameters and returns trueif the first one should come before the second one, and falseotherwise:

//same pairs as before
val t1 = (5, "foo")
val t2 = (19, "bar")
val t3 = (12, "baz")
val t4 = (5, "qux")

//a custom ordering function that always puts pairs whose
//second elements are words starting with "b" before others
List(t1, t2, t3, t4).sortWith((a, b) => {
   if (a._2.startsWith("b")) true
   else false
//List((12,baz), (19,bar), (5,foo), (5,qux))

Dialogue & Discussion