Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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

like image 355
Vonn Avatar asked Jun 19 '10 02:06

Vonn


People also ask

How do I convert a list to map in Scala?

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.

What is TreeMap in Scala?

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.

What is difference between map and HashMap in Scala?

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.

Are maps ordered in Scala?

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.


2 Answers

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 
like image 172
Ben Lings Avatar answered Sep 19 '22 20:09

Ben Lings


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.

like image 24
sblundy Avatar answered Sep 20 '22 20:09

sblundy