删除地图列表的选项

时间:2016-08-10 15:12:34

标签: scala

我有一张类型的地图:

Map[Int, Seq[Option[User]]]

我想将其转换为:

Map[Int, Seq[User]]

我只想从Seq。

中删除任何Option [User]

2 个答案:

答案 0 :(得分:6)

简单的Seq#flatten是神奇的:

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())

答案 1 :(得分:0)

yourMap.map({ case (key, seq) => { 
    (key, seq.filter(uOpt => !uOpt.isEmpty).map(_.get)) 
} })

或者,

val newMap = for {
  (key, seq) <- yourMap
  newSeq = for {
    userOpt <- seq
    if !userOpt.isEmpty
  } yield userOpt.get
} yield (key -> newSeq)