Question

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?

 45  29172  45
1 Jan 1970

Solution

 49

An alternative to using :_* as described by sblundy is to append the existing map to an empty SortedMap

import scala.collection.immutable.SortedMap
val m = Map(1 -> ("one":Any))
val sorted = SortedMap[Int, Any]() ++ m
2010-06-19

Solution

 45

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.

2010-06-19