Table of contents
1.
Introduction
2.
Using map() Function
3.
Using flatten() Function
4.
flatMap in Scala
5.
Using flatMap on a list of Strings
5.1.
Example
6.
flatMap Using Concatenation
6.1.
Example
7.
Using if else Statement
7.1.
Example
8.
Advantages of flatMap
9.
Frequently Asked Questions
9.1.
What is flatten method in Scala?
9.2.
What is a map() in Scala?
9.3.
What is a tuple in Scala?
9.4.
What is a zip in Scala?
9.5.
What is a fold in Scala?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

flatMap() in Scala

Author Sagar Mishra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hey Ninjas! You must have encountered the flatMap while working on Scala. Do you know flatMap in Scala is an essential part of collections? 

flatMap in Scala is a framework that comes under the collection. This blog will discuss all the features under the function flatMap in Scala.

flatMap() in Scala

Let's start without wasting our time.

Also see, Must Do Coding Questions

Using map() Function

This method accepts a function as an argument. Without altering the source list, apply the function to each element. Scala collections that are both mutable and immutable are also suitable. Let us take an example to understand this.

Example:

object codingNinjas
{
	def main(args:Array[String])
	{
		val collection = List(100, 400, 500)
		val newly_formed_coll = collection.map(x => x-20)
		println(newly_formed_coll)
	}
}


Output

map example Output

Recommended Topic About, 8085 Microprocessor Pin Diagram

Using flatten() Function

The flatten function is a member of the GenericTraversableTemplate trait, but there are technical versions of the flatten methods for given collection types.

Let us take an example to understand this.

object codingNinjas{
	def main(args:Array[String]){
    	val list = Seq("two", "three", "four", "six", "eight")
    	println("before" + list)
    	var newList = list.flatten
    	println("aftr" + newList)
	}
}


Output

flatten example Output

flatMap in Scala

The flatMap() method is the process of removing the inner grouping of an item. This process generates a sequence. The flatMap method acts as a shorthand to map and instantly flatten a collection. In simple language, it breaks the given string into the characters present in it, separated by a comma.

Users can use this flat map method with mutable and immutable Scala collections. Mutable is something that can be changed. Immutable cannot be changed once set.

There are mainly three methods of using flatMap in Scala. 

  • Case 1: Using flatMap on a list of Strings
  • Case 2: flatMap using concatenation
  • Case 3: Using if else statement
     

Let's discuss them one by one.

Also Read About, YII Framework

Using flatMap on a list of Strings

In this unit, we will learn how to use flatMap in Scala on given Strings.

Syntax

The syntax of flatMap in Scala is as follows:

collection.flatMap(convFunc)


Explanation

The convFunc in the above syntax is a conversion function used for converting elements of the collection. There is a collection under which the flatMap function is located.

Example

object codingNinjas{
    def main(args: Array[String]) {
        val list = List("I", "Love", "Coding", "Ninjas") 
        print("Initial collection: " + list)
        
        val output = list.flatMap(_.toLowerCase) 
        print("\nMapped collection with function: " + output)
    }
}


Output

Using flatMap on a list of Strings Output

flatMap Using Concatenation

In this unit, we will learn how to use concatenation under flatMap in Scala.

Syntax

The syntax of flatMap using concatenation is given below:

collection.flatMap(x => x + "newString")


Explanation

Here, x is the input given at first while creating the collection. newString is the string given to add in the input string(x). flatMap can also be used to merge the given string into the output string. Let us check an example for more clearance.

Example

object codingNinjas extends App{
	// Creating a collection
	val collection = List("hi", "ninja")
	println(collection.flatMap(x => x + "hello"))
}


Output

flatMap using concatenation Output


You can also read about mock interview.

Using if else Statement

In this unit, we will learn how to use the if else statement under flatMap in Scala.

Syntax

The syntax of flatMap using the if-else statement is given below:

collection flatMap { x =>
                if (condition) statement
                else statement
                }


Explanation

Here, x is the given input string. Next, the compiler will check the condition given in the if block. If the condition is true, it will go inside the if block and execute the expression. If not, it will move to the else condition and perform the expression.

Example

object codingNinjas
{
    def main(args:Array[String])
    {
        val seq = Seq(7, 10, 12, 15, 19, 30)
        val result = seq flatMap { str =>
                if (str % 5 == 0) Seq(str)
                else Seq(-str)
        }
        println(result)
    }
}


Output

Using if else statement Output

Advantages of flatMap

Advantages

Some advantages of flatMap are as follows:

  • flatMap avoids the use of nested For Loops.
  • flatMap function is easy and simple to understand as a beginner.
  • flatMap does not use the callback hell feature.
  • flatMap functions offer a more readable code flow as compared to others.

Check out this article - C++ String Concatenation

Frequently Asked Questions

What is flatten method in Scala?

The GenericTraversableTemplate traits flatten() method returns a single collection of elements by combining child collections.

What is a map() in Scala?

An Iterable that has pairs of keys and values is known as a map (also named mappings or associations). The Predef object in Scala provides an implicit translation that lets you express the pair (key, value) using key -> value as an alternative syntax.

What is a tuple in Scala?

A tuple is a value in Scala that consists of a certain number of elements, each of which has a unique type. Tuples cannot be changed. When a method returns many values, tuples are extremely useful.

What is a zip in Scala?

The IterableLike trait's zip() method is used to combine a collection with the one that is currently being used. The result is a collection of pairwise tuple elements from the combined collection.

What is a fold in Scala?

Two sets of parameters are required by the fold method. A start value is present in one, while a combining function is present in the other. After that, it traverses the list, recursively applying the function on the next element of the list as well as an accumulated value.

Conclusion

In this article, we discussed the topic of flatMap in Scala. In detail, we have seen the definition of flatMap in Scala. Along with this, we have seen three different methods of using flatMap in Scala. These methods are discussed in three phases that are Syntax, Explanation, and Example. Later we discussed the advantages of flatMap in Scala.

We hope this blog has helped you enhance your knowledge of flatMap in Scala. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass