EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Scala flatMap

By Shalu SharmaShalu Sharma

Home » Software Development » Software Development Tutorials » Scala Tutorial » Scala flatMap

scala flatmap

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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.

Popular Course in this category
Scala Programming Training (3 Courses,1Project)3 Online Courses | 9+ Hours | Verifiable Certificate of Completion | Lifetime Validity | 1 Project
4.5 (5,548 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)All in One Software Development Bundle (600+ Courses, 50+ projects)

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:

Scala flatmap Example 1

Now in flaMap, you can use both these method together when you have a scenario like this:

  1. You creating a list a source list and want to modify its elements by using map() and create a new list.
  2. Newly created list by source list.
  3. 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:

Scala flatmap Example 2

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:

string Example 1

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:

Scala flatmap Example 2

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:

Uppercase Example 3

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 –

  1. Kotlin vs Scala | Top 10 C0mparison
  2. Overview of Scala Data Types
  3. Scala for Loop | Top 6 Examples
  4. Scala High Order Functions

Scala Programming Training (3 Courses)

3 Online Courses

9+ Hours

Verifiable Certificate of Completion

Lifetime Validity

1 Project

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Scala Tutorial
  • Advanced
    • Constructors in Scala
    • Scala Class Constructor
    • Scala Abstract Class
    • Scala String
    • Scala Collections
    • Scala High Order Functions
    • Scala Date Function
    • Scala Stream
    • Scala Class
    • Scala Function
    • Scala Closure
    • Scala Range
    • Scala Either
    • Scala Random
    • Scala Tuples
    • Scala Partial Function
    • Scala Split
    • Scala Finds
    • Scala List
    • Scala Trait
    • Scala Try Catch
    • Scala Regex
    • Scala Vector
    • Scala Seq
    • Scala Byte
    • Scala ListBuffer
    • Scala ArrayBuffer
    • Scala flatMap
    • Scala HashMap
    • Scala Map Function
    • Scala SortBy
    • Scala Some
    • Scala Generic
    • Scala getOrElse
    • Scala REPL
    • Scala Logging
    • Scala Lambda
    • Scala Queue
    • Scala Set
    • Scala Singleton
    • Scala groupBy
    • Scala reduce
    • Scala filter
    • Scala Option
    • Scala Native
    • Scala DataFrame
    • Scala Anonymous Function
    • Scala Read File
    • Scala Write to File
    • Scala Pattern Matching
    • Scala ClassTag
    • Scala Synchronized
    • Scala zipwithindex
    • Scala Interview Questions
  • Basics
    • What is Scala?
    • Uses of Scala
    • Scala Versions
    • Scala Data Types
    • Scala Companion Object
    • Scala Operators
    • Scala: The Functional Approach
    • Scala Object
    • Scala Implicit
    • Scala IDE
  • Control Flow
    • Scala if else
    • Break in Scala
    • Scala for Loop
    • Scala foreach
    • Scala While Loops

Related Courses

Scala Programming Training Course

Programming Language Course

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Scala Programming Training (3 Courses) Learn More