scalascala-collectionsscala-2.10scala-2.8

Scala: How can I split a String into a Map


Environment : Scala 2.10+ IDE : Eclipse Kepler

I have a line NAME=bala AGE=23 COUNTRY=Singapore

How can I get it as a map

Map(NAME -> bala, AGE -> 23, COUNTRY -> Singapore)


Solution

  • Yet another solution

    val str = "NAME=bala AGE=23 COUNTRY=Singapore"
    val pairs = str.split("=| ").grouped(2)
    val map = pairs.map { case Array(k, v) => k -> v }.toMap
    // Map(NAME -> bala, AGE -> 23, COUNTRY -> Singapore)