I would like to convert a Map[Int, Any]
to a SortedMap
or a TreeMap
. Is there an easy way to do it?
To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.
Companion object TreeMapAn immutable SortedMap whose values are stored in a red-black tree. This class is optimal when range queries will be performed, or when traversal in order of an ordering is desired.
Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. HashMap implements immutable map and uses hash table to implement the same.
Solution. Scala has a wealth of map types to choose from, and you can even use Java map classes. If you're looking for a basic map class, where sorting or insertion order doesn't matter, you can either choose the default, immutable Map , or import the mutable Map , as shown in the previous recipe.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With