August 2013
Intermediate to advanced
720 pages
16h 23m
English
You have an unsorted map and want to sort the elements in the map by the key or value.
Given a basic, immutable Map:
scala>val grades = Map("Kim" -> 90,|"Al" -> 85,|"Melissa" -> 95,|"Emily" -> 91,|"Hannah" -> 92|)grades: scala.collection.immutable.Map[String,Int] = Map(Hannah -> 92, Melissa -> 95, Kim -> 90, Emily -> 91, Al -> 85)
You can sort the map by key, from low to
high, using sortBy:
scala>import scala.collection.immutable.ListMapimport scala.collection.immutable.ListMap scala>ListMap(grades.toSeq.sortBy(_._1):_*)res0: scala.collection.immutable.ListMap[String,Int] = Map(Al -> 85, Emily -> 91, Hannah -> 92, Kim -> 90, Melissa -> 95)
You can also sort the keys in ascending or descending order using
sortWith:
// low to high scala>ListMap(grades.toSeq.sortWith(_._1 < _._1):_*)res0: scala.collection.immutable.ListMap[String,Int] = Map(Al -> 85, Emily -> 91, Hannah -> 92, Kim -> 90, Melissa -> 95) // high to low scala>ListMap(grades.toSeq.sortWith(_._1 > _._1):_*)res1: scala.collection.immutable.ListMap[String,Int] = Map(Melissa -> 95, Kim -> 90, Hannah -> 92, Emily -> 91, Al -> 85)
You can sort the map by value using sortBy:
scala> ListMap(grades.toSeq.sortBy(_._2):_*)
res0: scala.collection.immutable.ListMap[String,Int] =
Map(Al -> 85, Kim -> 90, Emily -> 91, Hannah -> 92, Melissa -> 95)You can also sort by value in ascending or descending order using
sortWith:
// low to high
scala> ListMap(grades.toSeq.sortWith(_._2 ...Read now
Unlock full access