2

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)
  }
Mohammad Adnan
  • 6,527
  • 6
  • 29
  • 47

3 Answers3

5

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
Community
  • 1
  • 1
ymonad
  • 11,710
  • 1
  • 38
  • 49
2

similar to above but using only 'map'

ar.map(_.split("=")).map(a=>(a(0), a(1))).toMap
hi_my_name_is
  • 4,894
  • 3
  • 34
  • 50
  • then its your IDE, try using File->Invalidates caches and restart. You can always verify one line solutions in scala repl just to be sure your IDE is not messing with you :) – hi_my_name_is Oct 21 '16 at 06:56
0

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

Aravindh S
  • 1,185
  • 11
  • 19