Domanda

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)

È stato utile?

Soluzione

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)

Altri suggerimenti

I came up to something like this, but I'm almost sure there is a more efficient way:

val line = "NAME=bala AGE=23 COUNTRY=Singapore"
line.split(" ").map(_.split("=")).map(arr => arr(0) -> arr(1)).toMap

This gave me:

res10: scala.collection.immutable.Map[String,String] = Map(NAME -> bala, AGE -> 23, COUNTRY -> Singapore)

Use regex:

val line = "NAME=bala AGE=23 COUNTRY=Singapore"

val regex = """(\w+)=(\w+)""".r
val map = line.split("\\s+") map { elem =>
  val regex(key, value) = elem
  (key, value)
} toMap
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top