map, flatMap, filter and for comprehension in Scala

.map
When map is applied on some collection of type A, it returns a new collection of the same type with elements of type B.

    val list = List(1,2,3) // this is calling apply method on companion object
    println(list)
    // map
    println(list.map(_ + 1)) // returns List (same type) of type Int
    println(list.map(_ + " is a number")) // returns List (same type) of type String

.filter
Takes a lambda that takes one param and returns boolean. Values are filtered when boolean is true.

  println(list.filter(_ % 2 == 0)) // prints 2

.flatMap
flatten (reduces) the hierarchy by one level each time it is applied

    val toPair = (x: Int) => List(x, x+1)
    println(list.flatMap(toPair))

Example with both map and flatMap

val numbers = List(1, 2, 3, 4)
    val chars = List('a', 'b', 'c', 'd')
    val colors = List("White", "Black")
    val combinations = numbers.flatMap(n => chars.flatMap(c => colors.map(co => c + "" + n + " " + co)))
    println(combinations)

for comprehensions
since the above maps and flatMaps are difficult to read, we use for comprehensions and the compiler will transform the for-comprehension to maps and flatMaps for us

    val forCombinations = for {
        n <- numbers
        c <- chars
        co <- colors
    } yield "" + c + "" + n + " " + co
    println(forCombinations)
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: