Scala Map and flatMap difference

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-10 13:04:18 Viewed : 237


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

Search
Sub-Categories
Related Articles

Leave a Comment: