-4

I am not able to understand the functioning of flatMap function on Map objects.

Avik Aggarwal
  • 599
  • 7
  • 28

3 Answers3

1

You use flatMap if you want to flatten your result from map-function. keep in mind:

flatMap(something)

is identical to

map(something).flatten
markusheilig
  • 178
  • 2
  • 6
1

I think it is good question, cause map cannot be flatten as other collections. First off all we should look at the signature of this method:

def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): Map[B]

So, the documentation says that it should return Map, but it is not true, cause it can return any GenTraversableOnce and not only it. We can see it in the provided examples:

def getWords(lines: Seq[String]): Seq[String] = lines flatMap (line => line split "\\W+")

// lettersOf will return a Seq[Char] of likely repeated letters, instead of a Set
def lettersOf(words: Seq[String]) = words flatMap (word => word.toSet)

// lettersOf will return a Set[Char], not a Seq
def lettersOf(words: Seq[String]) = words.toSet flatMap (word => word.toSeq)

// xs will be an Iterable[Int]
val xs = Map("a" -> List(11,111), "b" -> List(22,222)).flatMap(_._2)

// ys will be a Map[Int, Int]
val ys = Map("a" -> List(1 -> 11,1 -> 111), "b" -> List(2 -> 22,2 -> 222)).flatMap(_._2)

So let look at the full signature:

def flatMap[B, That](f: ((K, V)) ⇒ GenTraversableOnce[B])(implicit bf: CanBuildFrom[Map[K, V], B, That]): That

Now we see it returns That - something that implicit CanBuildFrom can provide for us.

You can find many explanation how CanBuildFrom works. But the main idea is put some function from your key -> value pair to GenTraversableOnce, it can be some Map, Seq or even Option and it will be mapped and flattened. Also you can provide your own CanBuildFrom.

0

If you have a value or a key in the Map having a list then it can be flatMap-ed.

Example:

val a = Map(1->List(1,2),2->List(2,3))

a.map(_._2) gives List(List(1,2),List(2,3))

you can flatten this using flatMap => a.flatMap(_._2) or a.map(_._2).flatten gives List(1,2,2,3)

src: http://www.scala-lang.org/old/node/12158.html

Not sure about any other way of using flatMap on a Map though.