‘map‘, ‘flatMap‘, and ‘filter‘ are higher-order functions in Scala that are commonly used with collections like List, Array, Set, or Map. They provide a more functional and concise way of manipulating data in collections. Let’s discuss each one of them and understand the differences.
1. ‘map‘: The ‘map‘ function takes a function as an argument and applies this function to each element of the collection, creating a new collection with the results. The signature of ‘map‘ is:
def map[B](f: (A) => B): List[B]
Here’s an example:
val numbers = List(1, 2, 3, 4)
val squaredNumbers = numbers.map(x => x * x)
// squaredNumbers: List(1, 4, 9, 16)
2. ‘flatMap‘: The ‘flatMap‘ function also takes a function as an argument, but this function must return a collection. It applies this function to each element of the original collection and then concatenates (or "flattens") the result into a single collection. The signature of ‘flatMap‘ is:
def flatMap[B](f: (A) => Iterable[B]): List[B]
Here’s an example:
val words = List("hello", "world")
val characters = words.flatMap(word => word.toList)
// characters: List('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
3. ‘filter‘: The ‘filter‘ function takes a predicate function, i.e., a function that takes an element and returns a boolean value, as an argument. It applies this predicate function to each element of the collection and creates a new collection with the elements for which the predicate function returns ‘true‘. The signature of ‘filter‘ is:
def filter(p: (A) => Boolean): List[A]
Here’s an example:
val numbers = List(1, 2, 3, 4, 5, 6)
val evenNumbers = numbers.filter(x => x % 2 == 0)
// evenNumbers: List(2, 4, 6)
In summary, the main differences between ‘map‘, ‘flatMap‘, and ‘filter‘ in Scala collections are:
- ‘map‘: applies a function to each element, keeping the same number of elements in the resulting collection.
- ‘flatMap‘: applies a function that returns a collection to each element and then flattens the results into a single collection.
- ‘filter‘: creates a new collection containing the elements that satisfy a given predicate function.