Scala Map and flatMap difference

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-10 07:34:18 Viewed : 554


Scala Map and flatMap difference

When we collect two lists, given below

Without flat map => [1,2],[1,1] => [[1,2],[1,1]] Here two lists are placed inside a list, so the output will be list containing lists

With flat map => [1,2],[1,1] => [1,2,1,1] Here two lists are flattened and only the values are placed in list, so the output will be list containing only elements

Basically it merges all the objects in to one

Example:

Following example illustrates about Scala Map and flatMap diffrence

Save the file as −  MapFlatMap.scala 

MapFlatMap.scala  

 package runnerdev 

object MapFlatMap extends App { 

  val array1d = Array("1,2,3""4,5,6""7,8,9")

  //array1d is an array of strings

  //val mapArray: Array[Array[String]]

  var mapArray = array1d.map(x => x.split(","))

  //mapArray will be : Array( Array(1,2,3), Array(4,5,6), Array(7,8,9) )

  println("mapArray:")

  mapArray.foreach(a => a.foreach(println(_)))

 

  //val flatArray: Array[String]

  var flatArray = array1d.flatMap(x => x.split(","))

  //flatArray will be : Array (1,2,3,4,5,6,7,8,9)

  println("flatArray:")

  flatArray.foreach(println(_)) 

}  

  

Compile and run the above example as follows −

C:>scalac MapFlatMap.scala

C:>scala MapFlatMap 

Output:

mapArray:

1

2

3

4

5

6

7

8

9

flatArray:

1

2

3

4

5

6

7

8

9

In Scala, map and flatMap are both higher-order functions used for working with collections, but they serve different purposes and have different behaviors. Here is an explanation of their differences along with examples:

1. map Function:

  • The map function is used to transform each element of a collection while maintaining the structure of the original collection.

  • It takes a function that operates on each element of the collection and returns a new collection with the same structure (e.g., same length) as the original.

  • The result of map is a collection of the same type (e.g., if you map a List, you get back a List).

Example of map:

Suppose we have a list of integers and want to double each element:

scala
val originalList = List(1, 2, 3, 4, 5) val doubledList = originalList.map(x => x * 2)

Output:

css
originalList: List(1, 2, 3, 4, 5) doubledList: List(2, 4, 6, 8, 10)

In this example, map transforms each element by doubling it while preserving the list structure.

2. flatMap Function:

  • The flatMap function is used when you want to transform each element of a collection into a sequence of elements and then flatten the sequences into a single collection.

  • It takes a function that operates on each element of the collection and returns a collection (often a Seq, List, or Set) for each element. The results are then flattened into a single collection.

  • The result of flatMap is typically a collection of a different type (e.g., if you flatMap a List, you might get back a List of elements or a different collection type).

Example of flatMap:

Suppose we have a list of strings representing sentences, and we want to split each sentence into words and flatten them into a single list:

scala
val sentences = List("Hello, World!", "Scala is awesome.", "Functional programming.") val words = sentences.flatMap(sentence => sentence.split(" "))

Output:

css
sentences: List("Hello, World!", "Scala is awesome.", "Functional programming.") words: List("Hello,", "World!", "Scala", "is", "awesome.", "Functional", "programming.")

In this example, flatMap splits each sentence into words, creating lists of words for each sentence, and then flattens these lists into a single list of words.

In summary, map is used for one-to-one transformations of elements, while flatMap is used when you need to transform elements into collections and flatten the result into a single collection. The choice between map and flatMap depends on your specific use case and the desired result structure.

Search
Related Articles

Leave a Comment: