Scala: How can I split a String into a Map
Asked Answered
D

3

7

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)

Dorsad answered 28/2, 2014 at 8:54 Comment(0)
C
19

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)
Circumambient answered 28/2, 2014 at 9:11 Comment(1)
I just came up to the exact solution. Nice oneScamander
S
7

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)
Scamander answered 28/2, 2014 at 9:8 Comment(0)
F
1

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
Foolery answered 28/2, 2014 at 9:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.