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?
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With