I have a collection of Option[T]
, and now I want to extract values from it. But I also want the new collection to exclude None
s.
val foo = List(None, None, Some(1), None, Some(2))
The first idea came to my mind is map
, but it's a little unintuitive.
foo.map(o => o.get) // Exception!
foo.map(o => o.getOrElse(null)).filterNot(_ == null) // List(1, 2), works but not elegant
Is there a simpler way to achieve this behavior?
Use flatten
method:
scala> val foo = List(None, None, Some(1), None, Some(2))
foo: List[Option[Int]] = List(None, None, Some(1), None, Some(2))
scala> foo.flatten
res0: List[Int] = List(1, 2)
Just to be complete, there is also flatMap method:
foo.flatMap(x => x)
and for-comprehension:
scala> for(optX <- foo; x <- optX) yield x
res1: List[Int] = List(1, 2)
and collect (acts like filter + map):
scala> foo.collect { case Some(x) => x }
res2: List[Int] = List(1, 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With