How to convert String to Seq [String] on the map

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

+4
source share
2 answers
 original.mapValues(Seq(_)) 

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

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

Using:

 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)) 
+9
source

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

If t is Tuple2 , f <-: t :-> g 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)) 
+2
source

Source: https://habr.com/ru/post/1391685/


All Articles