Home »
Scala
flatMap() Method in Scala
By IncludeHelp Last updated : November 15, 2024
The flatMap() Method
flatMap() method in scala is one method that is similar to the map() method in Scala.
The flatMap() method is used to transform one collection to others based on the value of the passed conversion function. The main function that flatMap() serves is that it removes the inner grouping of the elements of the collection and convert it to a collection of degenerate elements.
The flatMap() method is simply the sum of map() and flattern() . The collections will be transformed using map() method followed by flattern() method.
Syntax
collection.flatMap(convFunc)
Parameters
- convFunc - It is a conversion function that is used for the conversion of elements of the collection.
Return Value
The function returns a new collection of the same type as the initial function.
Example 1: Using flatMap() on a sequence of strings and flatern it
// Program to illustrate the working of
// flatMap() function
object MyObject {
def main(args: Array[String]): Unit = {
val coll1 = List("Scala", "Programming", "Language")
print("Initial collection: " + coll1)
val coll2 = coll1.flatMap(_.toLowerCase)
print("\nMapped collection with function to multiply by 2: " + coll2)
}
}
Output
Initial collection: List(Scala, Programming, Language)
Mapped collection with function to multiply by 2:
List(s, c, a, l, a, p, r, o, g, r, a, m, m, i, n, g, l, a, n, g, u, a, g, e)
Explanation
In the above code, we have created a collection coll1 which is a list of string. Then we will use the flatMap() method to transform the collection. And we have used the _toLowerCase method which is passed to the method. And then print the new list.
Example 2: Working of flatMap() with seq and flaterning seq of seq
// Program to illustrate the working of
// flatMap() function
object MyObject {
def createSeq(a:Int) = Seq(a, a*a, a*a*a);
def main(args: Array[String]): Unit = {
val coll1 = Seq(6, 1, 8, 2, 9, 5)
print("Initial collection: " + coll1)
val coll2 = coll1.flatMap(createSeq)
print("\nMapped collection with function to multiply by 2: " + coll2)
}
}
Output
Initial collection: List(6, 1, 8, 2, 9, 5)
Mapped collection with function to multiply by 2:
List(6, 36, 216, 1, 1, 1, 8, 64, 512, 2, 4, 8, 9, 81, 729, 5, 25, 125)
Explanation
In the above code, we have created a list coll1 which of integer and then used the flatMap() method to transform it. The function used takes each element of the list and then converts it to a list of the number, its square and cube. And the flatMap() transforms and flaterns it to a list. Then we have printed the output.