scala> val i = List("Apple", "Banana", "Orange")
i: List[String] = List(Apple, Banana, Orange)
scala> i.map(x => x.toUpperCase)
res2: List[Char] = List(APPLE, BANANA, ORANGE)
flatMap is loop thru all element, flatten the element and apply a function into it.scala> val i = List("Apple", "Banana", "Orange")
i: List[String] = List(Apple, Banana, Orange)
scala> i.flatMap(x => x.toUpperCase)
res2: List[Char] = List(A, P, P, L, E, B, A, N, A, N, A, O, R, A, N, G, E)
Here is an example on different between map and flatMap in List(List(), List())scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)
scala> def x(v:Int) = List(v,v+1)
x: (v: Int)List[Int]
scala> l.map(i => x(i))
res5: List[List[Int]] = List(List(1, 2), List(2, 3), List(3, 4))
scala> l.flatMap(i => x(i))
res6: List[Int] = List(1, 2, 2, 3, 3, 4)
Here is an example on different between map and flatMap in Option (None and Some). flatMap remove empty value (None).scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)
scala> def f(x:Int) = if (x > 2) Some(x) else None
f: (x: Int)Option[Int]
scala> l.map( x => f(x))
res11: List[Option[Int]] = List(None, None, Some(3), Some(4), Some(5))
scala> l.flatMap( x => f(x))
res12: List[Int] = List(3, 4, 5)
References:http://www.brunton-spall.co.uk/post/2011/12/02/map-map-and-flatmap-in-scala/
http://alvinalexander.com/scala/collection-scala-flatmap-examples-map-flatten
No comments:
Post a Comment