Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a list of (A, Option[B]) and extracting value from Option

I have a List[(A, Option[B])]. I would like to filter out all of the tuples containing a None in the second element and then "unwrap" the Option, giving a List[A, B].

I am currently using this:

list.filter(_._2.isDefined).map(tup => (tup._1, tup._2.get))

Is there a better way (more concise)?

like image 558
Ralph Avatar asked Mar 19 '23 09:03

Ralph


1 Answers

You can do it with pattern matching and collect:

list.collect { case (a, Some(b)) => (a, b) }
like image 87
Michael Zajac Avatar answered Mar 21 '23 03:03

Michael Zajac