deamon
deamon

Reputation: 92367

Get all entries having a value from List[Option] in Scala

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

Answers (3)

Arg
Arg

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

drexin
drexin

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

Faiz
Faiz

Reputation: 16245

Note that

 list.flatten

Will do just as well.

Upvotes: 49

Related Questions