Reputation: 92367
Is it possible to get all entries of a List[Option[T]]
having a value?
Example:
val list = List(None, Some(1), None, Some(2))
list.filter(_.isDefined).map(_.get)
result:
List[Int] = List(1, 2)
Is there a method to do it in one step? It's a common case, isn't it?
Upvotes: 22
Views: 8657
Reputation: 1916
You can also use:
list.flatMap( x => x)
scala> val a = List(None, Some(1), None, Some(2))
a: List[Option[Int]] = List(None, Some(1), None, Some(2))
scala> a.flatMap(x => x)
res0: List[Int] = List(1, 2)
For explanation of how/why this works, you might check out this article: http://www.brunton-spall.co.uk/post/2011/12/02/map-map-and-flatmap-in-scala/
Upvotes: 4
Reputation: 24413
Yes, you can use collect
for that:
list.collect { case Some(x) => x }
collect
takes a PartialFunction[A,B]
and applies this function to all the elements on which it is defined and discards the rest.
edit:
As gpampara correctly mentioned, for this case flatten
will be sufficient. collect
would be the right tool if there were additional constraints and/or transforming.
Upvotes: 10