Scala Map, FlatMap

In scala, we can map a value to an another value without affecting the original value. For that we can use map method.

Please note that map is not a Map collection in Java.

There are two kinds of mapping can be done.

Map and FlatMap

Map => This maps the value to another value
FlatMap => This maps the value first and then flatten it

If a flatMap applied on a collection of string means, then it will return List[List[String]]

Please refer the below example to know more.


package com.scala

object MapTest {

  def main(args: Array[String]) {
    val fruits = List("apple","orange", "pineapple")
    //Print the contents
    println(fruits)
    //Convert into map
    println(fruits.map(_.toUpperCase()))
    //Convert into FlatMap
    println(fruits.flatMap(_.toUpperCase()))
  }
}

Output:

List(apple, orange, pineapple)
List(APPLE, ORANGE, PINEAPPLE)
List(A, P, P, L, E, O, R, A, N, G, E, P, I, N, E, A, P, P, L, E)

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s