views:

171

answers:

5
+8  A: 

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))
Randall Schulz
Another trick to know is that `Map`'s `++` method takes a `TraversaleOnce` so you could use `st` like so: `Map[String, String]() ++ st.flatMap(n => n)`. Randal's way is better.
pr1001
Thank you for your fast answer. My problem was not the flatMap instead of map (although this is also helpful), but not knowing the <pre><code>Map(Seq(A,B) : _*) </pre></code> constructor.
Thirdman
+3  A: 

It's also worth seeing Randall's solution in for-comprehension form, which might be clearer, or at least give you a better idea of what flatMap is doing.

Map.empty ++ (for(possiblePair<-sPairs.split(";"); pair<-dynamicListExtract(possiblePair)) yield pair)
Dave Griffith
+6  A: 

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)].

Ben Lings
I think that was I was actually looking for. Thank you!
Thirdman
A: 

A simple solution (not handling error cases):

val str = "A>Aus;B>Ber"
var map = Map[String,String]()

str.split(";").map(_.split(">")).foreach(a=>map += a(0) -> a(1))

but Ben Lings' is better.

hbatista
A: 
val str= "A>Augsburg;B>Berlin"

Map(str.split(";").map(_ split ">").map(s => (s(0),s(1))):_*)

--or--

str.split(";").map(_ split ">").foldLeft(Map[String,String]())((m,s) => m + (s(0) -> s(1)))
Landei