Mohammad Adnan Mohammad Adnan - 11 months ago 51
Scala Question

Converting command line argument key=value pair to Map in scala

in my main program i receive inputs like -
key1=value1 key2=value2

Now what I want is to create a map out of it. I know the imperative way of doing this where I would get Array[String] that can be foreach and then split by "=" and then key and value can be used to form a Map.

is there a good functional and readable way to achieve this?
Also It will be great if I can avoid mutable Map and I want to avoid initial Dummy value initialization.

def initialize(strings: Array[String]): Unit = {
val m = collection.mutable.Map("dummy" -> "dummyval")
s => {
val keyVal:Array[String] = s.split("=")

m += keyVal(0) -> keyVal(1)


Answer Source

you can just use toMap().

However, converting from array to tuple is not quite trivial: How to convert an Array to a Tuple?

scala> val ar = Array("key1=value1","key2=value2")
ar: Array[String] = Array(key1=value1, key2=value2)

scala> ar.collect(_.split("=") match { case Array(x,y) => (x,y)}).toMap
res10: scala.collection.immutable.Map[String,String] = Map(key1 -> value1, key2 -> value2)

Maybe you have to call Function.unlift for intellij

val r = ar.collect(Function.unlift(_.split("=") match { case Array(x, y) => Some(x, y)})).toMap