Home > OS >  Convert a Seq["key1=val1"] to a Map[String, String] in Scala
Convert a Seq["key1=val1"] to a Map[String, String] in Scala

Time:12-14

I have the following Seq[String], with all strings with = delimiter.

keysVals = ["Country=France", "City=Paris"]

I would like to convert it into a Map[String, String], such as

result = Map("Country"->"France", "City"->"Paris")

How to do that, please?

CodePudding user response:

With Regex pattern-matching:

val x = List("Country=France", "City=Paris")
val KeyValuePattern = "([^=] )=([^=] )".r
val y = x.map { case KeyValuePattern(k, v) => (k -> v) }.toMap
println(y)

With good old String.split:

val x = List("Country=France", "City=Paris")
println(x.map(str => str.split("=") match { case Array(k, v) => (k -> v) }).toMap)
  • Related