环境:Scala 2.10+ IDE:Eclipse Kepler
我有一条线
NAME=bala AGE=23 COUNTRY=Singapore
如何将其作为地图
Map(NAME -> bala, AGE -> 23, COUNTRY -> Singapore)
答案 0 :(得分:13)
另一种解决方案
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)
答案 1 :(得分:6)
我想到了这样的事情,但我几乎肯定有一种更有效的方式:
val line = "NAME=bala AGE=23 COUNTRY=Singapore"
line.split(" ").map(_.split("=")).map(arr => arr(0) -> arr(1)).toMap
这给了我:
res10: scala.collection.immutable.Map[String,String] = Map(NAME -> bala, AGE -> 23, COUNTRY -> Singapore)
答案 2 :(得分:0)
使用正则表达式:
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