Last Updated: February 25, 2016
· eranation

Scala tip of the day - Array to Map, and sorting an existing Map by keys

From String Array to index Map in one line

Let's say you have a String Array of unique values, e.g. an Array of column names. And let's say you need to look them up in an efficient way, and get the index by name.

In Java, you would simply create a new HashMap, iterate over the array, and put the String value as key, and the index as the value.

In Scala there is a much nicer and more concise way

val indexByColName = columns.view.zipWithIndex.toMap

Sort existing Map by it's keys

Let's say you have an existing map (e.g. the map from the previous example) and you want to sort it, here is a quick snippet that does it

val map = ... //some Map
val sortedMap = TreeMap(map.toSeq:_*)

That's all, now if you ask yourself what is the _* thing is, the short answer is that it's used to tell the compiler to pass each element of the sequence individually for a function / method that accepts varargs

The long answer can be found here