Scala | flatMap Method

29 Apr, 2019
In Scala, flatMap() method is identical to the map() method, but the only difference is that in flatMap the inner grouping of an item is removed and a sequence is generated. It can be defined as a blend of map method and flatten method. The output obtained by running the map method followed by the flatten method is same as obtained by the flatMap(). So, we can say that flatMap first runs the map method and then the flatten method to generate the desired result.Note:
It has a built-in Option class as an Option can be expressed as a sequence which has at most one element i.e, either its empty or has only one element.
The flatten() method is utilized to disintegrate the elements of a Scala collection in order to construct a single collection with the elements of similar type.
Let’s see an example to illustrate, how the flatMap is working.
val name = Seq("Nidhi", "Singh")

Case 1:let’s apply map() and flatten() on the stated sequence.
// Applying map()val result1 = name.map(_.toLowerCase)
// OutputList(nidhi, singh)
// Applying flatten() now,val result2 = result1.flatten
// OutputList(n, i, d, h, i, s, i, n, g, h)
Case 2:let’s apply flatMap() directly on the given sequence.
name.flatMap(_.toLowerCase)
 
// Output
List(n, i, d, h, i, s, i, n, g, h)

So, we can see here that the output obtained in both the cases is same therefore, we can say that flatMap is a combination of map and flatten method.Now, let’s see some examples of flatMap method.
Utilizing flatMap on a sequence of Strings.Example:// Scala program of flatMap  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {          // Creating a sequence of strings        val portal = Seq("Geeks", "for", "Geeks")          // Applying flatMap        val result = portal.flatMap(_.toUpperCase)          // Displays output        println(result)      }}Output:List(G, E, E, K, S, F, O, R, G, E, E, K, S)
Here, flatMap is applied to the stated sequence so, a list of sequence of characters is generated.
// Scala program of flatMap  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {          // Creating a sequence of strings        val portal = Seq("Geeks", "for", "Geeks")          // Applying flatMap        val result = portal.flatMap(_.toUpperCase)          // Displays output        println(result)      }}
List(G, E, E, K, S, F, O, R, G, E, E, K, S)

Here, flatMap is applied to the stated sequence so, a list of sequence of characters is generated.
Applying flatMap with another functions.Example :// Scala program of flatMap  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {          // Creating a list of numbers        val list = List(2, 3, 4)          // Defining a function        def f(x:Int) = List(x-1, x, x+1)          // Applying flatMap        val result = list.flatMap(y => f(y))          // Displays output        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 :// Scala program of flatMap  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {          // Creating a sequence of numbers        val seq = Seq(4, 5, 6, 7)          // Applying flatMap on another        // function        val result = seq flatMap { s =>                        Seq(s, s-1)        }          // Displays output        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.
// Scala program of flatMap  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {          // Creating a list of numbers        val list = List(2, 3, 4)          // Defining a function        def f(x:Int) = List(x-1, x, x+1)          // Applying flatMap        val result = list.flatMap(y => f(y))          // Displays output        println(result)      }}
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 :
// Scala program of flatMap  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {          // Creating a sequence of numbers        val seq = Seq(4, 5, 6, 7)          // Applying flatMap on another        // function        val result = seq flatMap { s =>                        Seq(s, s-1)        }          // Displays output        println(result)      }}
List(4, 3, 5, 4, 6, 5, 7, 6)

Here, also output is obtained like the first example of the flatMap with another functions.
Utilizing flatMap on if-else statements.Example :// Scala program of flatMap  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {          // Creating a sequence of numbers        val seq = Seq(8, 15, 22, 23, 24)          // Applying flatMap on if-else        // statement        val result = seq flatMap { s =>                if (s % 3 == 0) Seq(s)                else Seq(-s)        }          // Displays output        println(result)    }}Output:List(-8, 15, -22, -23, 24)
Here, if an element of the sequence given satisfies the stated condition then that element is returned else negative of that element is obtained.
// Scala program of flatMap  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {          // Creating a sequence of numbers        val seq = Seq(8, 15, 22, 23, 24)          // Applying flatMap on if-else        // statement        val result = seq flatMap { s =>                if (s % 3 == 0) Seq(s)                else Seq(-s)        }          // Displays output        println(result)    }}
List(-8, 15, -22, -23, 24)

Here, if an element of the sequence given satisfies the stated condition then that element is returned else negative of that element is obtained.
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.