I have a map of type:
Map[Int, Seq[Option[User]]]
I want to transform this to:
Map[Int, Seq[User]]
I just want to remove any Option[User] from the Seq.
I have a map of type:
Map[Int, Seq[Option[User]]]
I want to transform this to:
Map[Int, Seq[User]]
I just want to remove any Option[User] from the Seq.
Simple Seq#flatten does the magic:
scala> Map(1 -> Seq(Option(1),None, Option(3),None), 2 -> Seq(None))
res1: Map[Int,Seq[Option[Int]]] =
Map(1 -> List(Some(1), None, Some(3), None), 2 -> List(None))
scala> res1.mapValues(_.flatten)
res2: Map[Int,Seq[Int]] = Map(1 -> List(1, 3), 2 -> List())
yourMap.map({ case (key, seq) => {
(key, seq.filter(uOpt => !uOpt.isEmpty).map(_.get))
} })
Or,
val newMap = for {
(key, seq) <- yourMap
newSeq = for {
userOpt <- seq
if !userOpt.isEmpty
} yield userOpt.get
} yield (key -> newSeq)