mkaz solutions log » home

How to Sort Collections in Scala

Date: Jun 28, 2011

Here is a list of examples sorting different data structures in Scala, Lists and Arrays

  // data structures working with
  val s = List( "a", "d", "F", "B", "e")
  val n = List(3, 7, 2, 1, 5)
  val m = Map(
    -2 -> 5, 
    2 -> 6, 
    5 -> 9, 
    1 -> 2,
    0 -> -16,
    -1 -> -4
  )

Using the built-in sorted method

  s.sorted
  res0: List[java.lang.String] = List(B, F, a, d, e)

  n.sorted
  res1: List[Int] = List(1, 2, 3, 5, 7)

  // NOTE: map object does not have sorted method

Case Insensitive Search

Use sortWith to create a custom comparison function for sorting case-insensitive.

  /* sort alphabetical and ignoring case */
  def compfn1(e1: String, e2: String) = (e1 compareToIgnoreCase e2) < 0

  /* sort alphabetical and ignoring case: alternate */
  def compfn2(e1: String, e2: String) = (e1.toLowerCase < e2.toLowerCase)

  s.sortWith(compfn1)
  res2: List[java.lang.String] = List(a, B, d, e, F)

  s.sortWith(compfn2)
  res3: List[java.lang.String] = List(a, B, d, e, F)

  /* Or you can do so using anonymous function (Thanks Rahul) */
  s.sortWith(_.toLowerCase < _.toLowerCase)
  res4: List[java.lang.String] = List(a, B, d, e, F)

How to Sort a Map by Key or Value

  // sort by key can use sorted
  m.toList.sorted foreach {
    case (key, value) =>
      println(key + " = " + value)
  }
  // sort by value
  m.toList sortBy ( _._2 ) foreach {
    case (key, value) =>
      println(key + " = " + value)
  }