Applying flatMap with another functions.
Example :
object GfG
{
def main(args : Array[String])
{
val list = List( 2 , 3 , 4 )
def f(x : Int) = List(x- 1 , x, x+ 1 )
val result = list.flatMap(y => f(y))
println(result)
}
}
|
Output:
List(1, 2, 3, 2, 3, 4, 3, 4, 5)
Here, flatMap is applied on the another function defined in the program and so a list of sequence of numbers is generated. Let’s see how the output is computed.
List(List(2-1, 2, 2+1), List(3-1, 3, 3+1), List(4-1, 4, 4+1))
// After evaluation we get,
List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))
So, first step works like applying map method on the another function stated.
List(1, 2, 3, 2, 3, 4, 3, 4, 5)
The second step works like applying flatten to the output obtained by the map method at the first step.
Example :
object GfG
{
def main(args : Array[String])
{
val seq = Seq( 4 , 5 , 6 , 7 )
val result = seq flatMap { s =>
Seq(s, s- 1 )
}
println(result)
}
}
|
Output:
List(4, 3, 5, 4, 6, 5, 7, 6)
Here, also output is obtained like the first example of the flatMap with another functions.