Scala: Filter None’s from a List[Option]

The simplest way to remove all the Options (both the Some wrappers and Nones) from a list is to flatten it:

List(
  Option("a"), 
  Option("b"), 
  None
).flatten

res39: List[String] = List(a, b)

You can achieve the same effect by using flatMap, which will allow you to modify the results if you need to (e.g. to change the type or modify the values):

List(
  Option("a"), 
  Option("b"), 
  None
).flatMap(
  x => x
)

If this isn’t want you want, you can also filter the list by whether the values are a None or not:

List(
  Option("a"), 
  Option("b"), 
  None
).filter(_.isDefined)

res40: List[Option[String]] = 
  List(Some(a), Some(b))

Leave a Reply

Your email address will not be published. Required fields are marked *