2020-08-06 Scala: map and flatMap

According to teacher Lin Ziyu's tutorial at Xiamen University:

Introduction to Scala: map operations and flatMap operations

The map operation is a typical transformation operation for a set. It applies a certain function to each element in the set and produces a result set.

flatMap is an extension of map. In flatMap, we will pass in a function that returns a collection (rather than an element) for each input. Then, flatMap will "flatten" the generated multiple collections into a collection.

Through the following comparison, you can see the difference between the two:

It can be seen that the flatMap operation is to do toList processing (Map) for each element first, and then stitch/flatten the processing results (collections) of each element.

Guess you like

Origin blog.csdn.net/authorized_keys/article/details/107831206