logo

Scala - Sorting

Sort A Collection

Use scala.util.Sorting.quickSort()

scala> val array = Array("b", "d", "a", "c")
array: Array[String] = Array(b, d, a, c)

scala> scala.util.Sorting.quickSort(array)

scala> array
res7: Array[String] = Array(a, b, c, d)

Use .sortBy()

Sort by String length

scala> val array = Array("bb", "d", "aaaa", "ccc")
array: Array[String] = Array(bb, d, aaaa, ccc)

scala> array.sortBy(_.length)
res0: Array[String] = Array(d, bb, ccc, aaaa)