In scala, how to get an array of keys and values ​​from the map, with the correct order (i-th key is for the i-th value)?

advertisements

say I have a map in Scala - key: String, value: String.

Is there an easy way to get the arrays of keys and values in corresponding order? E.g. the i-th element of the key array should be the key related to the i-th value of the values array.

What I've tried is iterating through the map and getting them one by one:

valuesMap.foreach{keyVal => keys.append(keyVal.1); values.append(keyVal.2); // the idea, not the actual code

Is there a simplier way?

The question could probably be asked: is there any way to guarantee a specific order of map.keys/map.values?

For example, when generating an SQL query it may be convenient to have arrays of column names and values separately, but with the same order.


You can use toSeq to get a sequence of pairs that has a fixed order, and then you can sort by the key (or any other function of the pairs). For example:

scala> val pairs = Map(3 -> 'c, 1 -> 'a, 4 -> 'd, 2 -> 'b).toSeq.sortBy(_._1)
res0: Seq[(Int, Symbol)] = ArrayBuffer((1,'a), (2,'b), (3,'c), (4,'d))

Now you can use unzip to turn this sequence of pairs into a pair of sequences:

scala> val (keys, vals) = pairs.unzip
keys: Seq[Int] = ArrayBuffer(1, 2, 3, 4)
vals: Seq[Symbol] = ArrayBuffer('a, 'b, 'c, 'd)

The keys and values will line up, and you've only performed the sorting operation once.