Map, FlatMap and Filter

Scala Comments

In this blog post, you’ll read about -

  1. Some basic operations on collections - Map, FlatMap and Filter (Duh!)

We’ll be working with a list of Ints :


A map operation is used to transform the list. Here’s the signature of map for the above list -

Let us understand the signature -

  1. 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.

  2. It returns a collection of type B (the transformed type).


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 -

  1. The function f takes in an Int and returns a Collection of type B.
  2. This level of nested structure is collapsed to return a collection of type B.
  1. Each and every operation in the flatMap returns a List.
  2. The flatten operation collapses this level of list.


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 -

  1. The function p takes in an Int (each and every element in the collection) and returns a Boolean.
  2. 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

Share this post