Map, FlatMap and Filter
In this blog post, you’ll read about -
- Some basic operations on collections - Map, FlatMap and Filter (Duh!)
We’ll be working with a list of Ints :
Map
A map operation is used to transform the list. Here’s the signature of map for the above list -
Let us understand the signature -
-
The map function takes in another function f. f takes in an Int (an item of the list - one at a time) and returns B.
-
It returns a collection of type B (the transformed type).
FlatMap
A flatMap operation is nothing but a map operation followed by a flatten operation. Flatten collapses one level of nested structure.
Let us understand this signature -
- The function f takes in an Int and returns a Collection of type B.
- This level of nested structure is collapsed to return a collection of type B.
- Each and every operation in the flatMap returns a List.
- The flatten operation collapses this level of list.
Filter
A Filter operation is used to filter out values from a collection based on some property of the element in the collection.
Let us understand this signature -
- The function p takes in an Int (each and every element in the collection) and returns a Boolean.
- The filter function returns a list of Int, all the elements that returned true for that function.
Final Note - As can be seen, these operations execute on 1 value at a time and hence really easy to parallelize. As a result, they’re commonly used in Scalding and Spark.
Kaushik Rangadurai
Code. Learn. Explore