scaladictionary

How do I convert a Map[Int, Any] to a SortedMap in Scala? Or a TreeMap?


I would like to convert a Map[Int, Any] to a SortedMap or a TreeMap. Is there an easy way to do it?


Solution

  • Assuming you're using immutable maps

    val m = Map(1 -> "one")
    val t = scala.collection.immutable.TreeMap(m.toArray:_*)
    

    The TreeMap companion object's apply method takes repeated map entry parameters (which are instances of Tuple2[_, _] of the appropriate parameter types). toArray produces an Array[Tuple2[Int, String]] (in this particular case). The : _* tells the compiler that the array's contents are to be treated as repeated parameters.