28 Working with List: map and flatMap
After reading this lesson, you will be able to:
- Transform the elements of a sequence using the map function
- Simplify a nested structure using the flatten method
- Manipulate and combine lists using the flatMap operation
- Chain instances of List using a for-comprehension statement
In the previous lesson, you have learned the basics of the type List of the Scala Standard Collection library. In this lesson, you are going to learn about the basic operations you can perform on lists: they are similar to their corresponding equivalent for the class Option. You will see how to use the map operation to apply a function to the elements of a sequence. You are going to discover how to unify nested lists using flatten, and how to chain them together using flatMap. You are also going to learn how to use a for-comprehension statement to combine and manipulate multiple lists into one. In the capstone, you will use the operations to extract information from the Movies Dataset.
28.1 The map, flatten, and flatMap operations
In the previous lesson you have represented the contacts of your address book using the following presentation:
case class Contact(name: String, surname: String, number: String)