Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to a Seq[String] in a Map

Tags:

scala

I have a Map[String,String] and a third party function that requires a Map[String,Seq[String]] Is there an easy way to convert this so I can pass the map to the function?

like image 431
chiappone Avatar asked Jan 18 '12 17:01

chiappone


2 Answers

original.mapValues(Seq(_))

Note that mapValues returns a map view, so the function (Seq(_)) will be recomputed every time an element is accessed. To avoid this, just use normal map:

original.map{ case (k,v) => (k, Seq(v)) }

Usage:

scala> val original = Map("a" -> "b", "c" -> "d")
original: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(a -> b, c -> d)

scala> original.mapValues(Seq(_))
res1: scala.collection.immutable.Map[java.lang.String,Seq[java.lang.String]] = Map(a -> List(b), c -> List(d))
like image 147
dhg Avatar answered Oct 17 '22 05:10

dhg


You could avoid some code duplication by using :-> from Scalaz.

If t is a Tuple2, f <-: t :-> g is equivalent to (f(t._1), g(t._2)).

scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._

scala> val m = Map(1 -> 'a, 2 -> 'b)
m: scala.collection.immutable.Map[Int,Symbol] = Map(1 -> 'a, 2 -> 'b)

scala> m.map(_ :-> Seq.singleton)
warning: there were 1 deprecation warnings; re-run with -deprecation for details
res15: scala.collection.immutable.Map[Int,Seq[Symbol]] = Map(1 -> List('a), 2 -> List('b))

scala> m.map(_ :-> (x => Seq(x)))
res16: scala.collection.immutable.Map[Int,Seq[Symbol]] = Map(1 -> List('a), 2 -> List('b))
like image 2
missingfaktor Avatar answered Oct 17 '22 06:10

missingfaktor