Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concise way to filter and map a scala sequence of tuples containing options

Tags:

scala

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.

like image 343
Raphael Roth Avatar asked Dec 18 '22 00:12

Raphael Roth


1 Answers

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.

like image 195
Xavier Guihot Avatar answered May 26 '23 21:05

Xavier Guihot