What is the shortest way to transform a Seq of Tuples, e.g.:
val xs : Seq[(Long,Option[Double])] = Seq((1L,None),(2L,Some(2.0)),(3L,None))
to a Seq[(Long,Double)]
by removing the Nones
I've used both
xs.filter(_._2.isDefined).map{case (i,x) => (i,x.get)}
and
xs.flatMap{
case (i,Some(x)) => Some(i,x)
case _ => None
}
But wonder if there is a shorter way. For a Seq[Option[Double]]
I would just do flatten
... but this does not work for nested Options.
You could use collect
which discards what's not part of your cases:
xs.collect{ case (i, Some(x)) => (i, x) }
In this case since case (i, None)
is not used, these cases will just be filtered out.
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