1
votes

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")
    strings.foreach(
      s => {
        val keyVal:Array[String] = s.split("=")

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

      })
    println(m)
  }
3

3 Answers

3
votes

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
2
votes

similar to above but using only 'map'

ar.map(_.split("=")).map(a=>(a(0), a(1))).toMap
0
votes

You can use Scopt to do the command line argument parsing in a neat way.