Search code examples
scalasplitpattern-matching

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


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?


Solution

  • The shortest way seems to be

    data.map { case s"${k}=${v}" => k -> v }.toMap
    

    using StringContext.s.unapplySeq as in

    val data = List("Country=France", "City=Paris")
    println(data.map { case s"${k}=${v}" => k -> v }.toMap)
    

    (thanks @Luis Miguel Mejía Suárez).


    Alternatively, with Regex pattern-matching:

    val KeyValuePattern = "([^=]+)=([^=]+)".r
    data.map { case KeyValuePattern(k, v) => k -> v }.toMap
    

    With good old String.split:

    data.map(str => str.split("=") match { case Array(k, v) => k -> v }).toMap