Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HowTo get a Map from a csv string

I'm fairly new to Scala, but I'm doing my exercises now.
I have a string like

"A>Augsburg;B>Berlin"
. What I want at the end is a map

val mymap = Map("A"->"Augsburg", "B"->"Berlin")

What I did is:

val st = locations.split(";").map(dynamicListExtract _)
with the function
private def dynamicListExtract(input: String)  = {
    if (input contains ">") {
      val split = input split ">"
      Some(split(0), split(1)) // return key , value
    } else {
      None 
    } 
  }
Now I have an
Array[Option[(String, String)
How do I elegantly convert this into a Map[String, String]

Can anybody help? Thanks

like image 999
Thirdman Avatar asked Jul 14 '10 15:07

Thirdman


2 Answers

Just change your map call to flatMap:

scala> sPairs.split(";").flatMap(dynamicListExtract _)
res1: Array[(java.lang.String, java.lang.String)] = Array((A,Augsburg), (B,Berlin))

scala> Map(sPairs.split(";").flatMap(dynamicListExtract _): _*)
res2: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map((A,Augsburg), (B,Berlin))

For comparison:

scala> Map("A" -> "Augsburg", "B" -> "Berlin")
res3: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map((A,Augsburg), (B,Berlin))
like image 103
Randall Schulz Avatar answered Sep 24 '22 11:09

Randall Schulz


In 2.8, you can do this:

val locations = "A>Augsburg;B>Berlin"
val result = locations.split(";").map(_ split ">") collect { case Array(k, v) => (k, v) } toMap

collect is like map but also filters values that aren't defined in the partial function. toMap will create a Map from a Traversable as long as it's a Traversable[(K, V)].

like image 45
Ben Lings Avatar answered Sep 23 '22 11:09

Ben Lings