What is the combination of flatMap and filter?
scala
Solution
Well, if you're trying to filter while using `flatMap` you can easily do something like
List(1, 2, 3).flatMap {
case n if n > 1 => List.fill(n)(n.toString)
case _ => Nil
}
// result: List("2", "2", "3", "3", "3")
In your specific case:
myList.flatMap { id => obj.foo(id) match {
case Some(list) => list
case None => Nil
}}
Or even shorter
myList.flatMap(obj.foo(_).getOrElse(Nil))
Problem
In scala collections, there is a collect method which is a combination of map and filter. Is there another method which is a combination of flatMap and filter? Here is what I am trying to do ``` val myList: List[Int] = .... val x = myList.flatMap { id => val r : Option[List[Int]] = obj.foo(id) r } ``` Right now the scala compiler tells me that the type of x is `List[List[Int]]` But I want `List[Int]` If I change my code to ``` val myList: List[Int] = .... val x = myList.flatMap { id => val r : Option[List[Int]] = obj.foo(id).get r } ``` Then I get what I want. but I don't want to do get. So I want a clean and concise way of doing a flatMap while filtering out the items which are None. I can also do ``` val myList: List[Int] = .... val result = myList.flatMap { id => val r : Option[List[Int]] = obj.foo(id).getOrElse(List[Int]()) r } ``` but that is still very verbose.