scala> List(List(1), List(2), List(3), List(4))
res18: List[List[Int]] = List(List(1), List(2), List(3), List(4))
scala> res18.flatten
res19: List[Int] = List(1, 2, 3, 4)
scala> res18.flatMap(identity)
res20: List[Int] = List(1, 2, 3, 4)
Is there any difference between these two functions? When is it appropriate to use one over the other? Are there any tradeoffs?
flatMap : regular map, but flattens the array afterwards. flatten : just call on an array and get a new flattened array.
flatMap , as it can be guessed by its name, is the combination of a map and a flat operation. That means that you first apply a function to your elements, and then flatten it. Stream. map only applies a function to the stream without flattening the stream.
The flatMap() method is similar to the map() method, but the only difference is that in flatMap, the inner grouping of an item is removed and a sequence is generated. The flatMap method acts as a shorthand to map a collection and then immediately flatten it.
mapper: It is a parameter that is a non-interfering, stateless function to apply to each element. It produces a stream of new values. In short, we can say that the flatMap() method helps in converting Stream<Stream<T>> to Stream<T>. It performs flattening (flat or flatten) and mapping (map), simultaneously.
You can view flatMap(identity)
as map(identity).flatten
. (Of course it is not implemented that way, since it would take two iterations).
map(identity)
gives you the same collection, so in the end it is the same as only flatten
.
I would personally stick to flatten
, since it is shorter/easier to understand and designed to exactly do this.
Conceptually there is no difference in the result...
flatMap
is taking bit more time to produce same result...
flatMap
, map
& then flatten
and flatten
object Test extends App { // flatmap println(timeElapsed(List(List(1, 2, 3, 4), List(5, 6, 7, 8)).flatMap(identity))) // map and then flatten println(timeElapsed(List(List(1, 2, 3, 4), List(5, 6, 7, 8)).map(identity).flatten)) // flatten println(timeElapsed(List(List(1, 2, 3, 4), List(5, 6, 7, 8)).flatten)) /** * timeElapsed */ def timeElapsed[T](block: => T): T = { val start = System.nanoTime() val res = block val totalTime = System.nanoTime - start println("Elapsed time: %1d nano seconds".format(totalTime)) res } }
Both flatMap
and flatten
executed with same result after repeating several times
flatten
is efficientElapsed time: 2915949 nano seconds List(1, 2, 3, 4, 5, 6, 7, 8) Elapsed time: 1060826 nano seconds List(1, 2, 3, 4, 5, 6, 7, 8) Elapsed time: 81172 nano seconds List(1, 2, 3, 4, 5, 6, 7, 8)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With