scala Iterable#map vs. Iterable#flatMap

21,967

Solution 1

Here is a pretty good explanation:

http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2

Using list as an example:

Map's signature is:

map [B](f : (A) => B) : List[B]

and flatMap's is

flatMap [B](f : (A) => Iterable[B]) : List[B]

So flatMap takes a type [A] and returns an iterable type [B] and map takes a type [A] and returns a type [B]

This will also give you an idea that flatmap will "flatten" lists.

val l  = List(List(1,2,3), List(2,3,4))

println(l.map(_.toString)) // changes type from list to string
// prints List(List(1, 2, 3), List(2, 3, 4))

println(l.flatMap(x => x)) // "changes" type list to iterable
// prints List(1, 2, 3, 2, 3, 4)

Solution 2

The above is all true, but there is one more thing that is handy: flatMap turns a List[Option[A]] into List[A], with any Option that drills down to None, removed. This is a key conceptual breakthrough for getting beyond using null.

Solution 3

From scaladoc:

  • map

Returns the iterable resulting from applying the given function f to each element of this iterable.

  • flatMap

Applies the given function f to each element of this iterable, then concatenates the results.

Solution 4

lines.map(line => line split "\\W+") // will return a list of arrays of words
lines.flatMap(line => line split "\\W+") // will return a list of words

You can see this better in for comprehensions:

for {line <- lines
     word <- line split "\\W+"}
yield word.length

this translates into:

lines.flatMap(line => line.split("\\W+").map(word => word.length))

Each iterator inside for will be translated into a "flatMap", except the last one, which gets translated into a "map". This way, instead of returning nested collections (a list of an array of a buffer of blah, blah, blah), you return a flat collection. A collection formed by the elements being yield'ed -- a list of Integers, in this case.

Share:
21,967
Landon Kuhn
Author by

Landon Kuhn

Updated on February 24, 2020

Comments

  • Landon Kuhn
    Landon Kuhn about 4 years

    What is the difference between the map and flatMap functions of Iterable?