Updated April 12, 2023
Introduction to Scala flatMap
In Scala flatmap method is used on the collection and data structures of scale, as the name suggests it is the combination of two things methods i.e. map and Flatten method. If we use a flat map on any collection then it will apply both this method map and flatten method on the given collection. We can use this flat map method with both immutable and mutable collections of Scala. Mutable is something that can be changed, immutable cannot be changed once assigned.
Syntax:
defflatMap[B](f: (A) =>IterableOnce[B]): List[B]
In the above syntax, it will iterate all the elements of the list and apply the function on all the elements of the list and prepare a new list with modified elements.
How flatMap Works in Scala?
The flatMap is the combination of two methods map and flatten method in Scala. Scala flatmap method generates a sequence it will break the grouping of input. We cannot say it is the combination of map and flatten but in actual it runs both method sequentially the first map then flatten method.
Flat map are like map only their implantation is provided by collection is the latest version but they are also present in some other classes as well and we can implement them in our class if needed, Some name of classes which already implement it are as follows :
- Try
- Option
- Future
let’s understand by each of them in detail how they work in order to understand the flat map method in Scala.
1. map()
This method takes a function as a parameter and applies the function on each element of the list without modifying the source list. It is also applicable for an immutable and mutable collection of Scala.
below are the Example:
Code:
//Example for begineers
object Main{
def main(args:Array[String])
{
// original collection or we can say source collection
val collection = List(100, 400, 500)
// modified collection
valnewly_formed_coll = collection.map(some_function)
println(newly_formed_coll)
}
}
In the above case, we are giving source collection and trying to modify it by using map and passing some function as a parameter but map returning new collection.
2. flatten()
Flatten method in Scala in a member of the GenricTraversableTemplate trait.
definition: def flatten[A]: Traversable[A]
Example for a beginner:
Code:
object Main{
def main(args:Array[String]){
// initilizing source list
val source = Seq("one", "two", "three", "four", "five")
println("before" + source)
vardes =source.flatten
println("aftr" + des)
}
}
Output:
Now in flaMap, you can use both these method together when you have a scenario like this:
- You creating a list a source list and want to modify its elements by using map() and create a new list.
- Newly created list by source list.
- You call flatten method after map method().
So this above case you can go for flatmap method of scala. It does all the three steps mentioned above. We can one example to understand how it works:
Code:
object Main extends App{
// create a colletion
val collection = List("hi", "bye")
println(collection.flatMap(x => x + "hello"))
}
Output:
Explanation: In the above example, we are using flat Map method to understand the functionality in details , First we are creating a collection which contains a list of string objects and then immediately after creation we are calling flat Map method on that particular collection and this flat Map method will give us newly created list. But here the elements of the list will be modified and will be a separate sequence of string rather than a group.
FlatMap is the method of TraversableLike
class definition of FlatMap as per Scala Documentation: classFlatMap[A, B] extends AbstractView[B]
It extends various classes such as:
- AbstarctView[B]
- View[B]
- AbstarctIterable
- Iterable
- IterableOnce
- IterableFactory
Also, a hierarchy is there for flatMap:
AbstractView =>FlatMap [A,B] =>IterableOnceExtensionMethod
Benefits of Scala flatMap
1. Parallel processing: We can also achieve parallel processing by using a flat map in Scala. We can easily make our newly created collection parallel by using Parallel collection, then by simply calling the function n newly created parallel collection will process the elements parallel It will also speed up the processing of elements.
Combine two methods as one: Here flatMap combines two methods functionality which as map and Examples.
2. flatten methods: By this, we can reduce or optimize our lines of code and make it efficient.
Examples to Implement Scala flatMap
Below are the examples of Scala flatMap:
Example #1
The example to show the map and flatten to demonstrate the same output by using two methods. This example will show how it works internally and how two methods can be replaced and code can be optimized for doing the same thing.
Code:
object Main extends App{
// Your code here!
val source = Seq("Bhaaa", "Amit", "Shah", "OPPOPOPOP", "ASHERERERE")
// here we are applying map method
val list1 = source.map(_.toLowerCase)
println("Here is the list1 with map() and befor flatten() " + list1)
// now flatten to seperate the string;
val list2 = list1.flatten
println("Here is the list2 with after flatten() " + list2)
}
Output:
Example #2
This example use flatMap() method to separate the input given.
Code:
object Main extends App{
// Your code here!
val source = Seq("Bhaaa", "Amit", "Shah", "OPPOPOPOP", "ASHERERERE")
println("list beforflatmap call ::" + source)
// we are directly calling flatmap here;
var list1 = source.flatMap(_.toLowerCase)
println("list after flatmap call ::" + list1)
}
Output:
Example #3
In this example, we are trying to convert the list of elements into uppercase by calling a function inside flatMap.
Code:
object Main{
def main(args:Array[String]){
// initilizing source list
val source = Seq("hnjik", "school" ,"new string", "old string", "learn")
println("elements before " + source)
// applying flatmap to modify list elemnts
var result = source.flatMap(_.toUpperCase)
println("elements aftre " + result)
}
}
Output:
Conclusion
flatMap in Scala are used to generate a separate set of sequence it is used with collection data structures and we can also use them with mutable and immutable collection objects. It also helps in faster processing of collection elements by making them parallel. Reduce the line of code. Also, we can give our own implementation if we want.
Recommended Articles
This is a guide to Scala flatMap. Here we discuss a brief overview of Scala flatMap and its Benefits along with different examples and code Implementation. You can also go through our other suggested articles to learn more –