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 for-comprehension

In the previous lesson, you learned the basics of the type List of the Scala standard collection library. In this lesson, you’ll learn about the basic operations you can perform on lists similar to those you have seen for the class Option. You will see how to use the map operation to apply a function to a sequence’s elements, unify nested lists using flatten, and chain them together using flatMap. You’ll learn how to use for-comprehension to combine and manipulate multiple lists into one. In the capstone, you will use operations to extract information from the movies data set.

28.1 The map, flatten, and flatMap operations

In the previous lesson, you represented the contacts of your address book using the following representation:

case class Contact(name: String, surname: String, number: String)

Suppose you now need to change your program to include extra information about each of your contacts. For example, you could track multiple phone numbers for the same contact and label them with a category, as well as store any email address or company name.

28.1.1 The map function

28.1.2 The flatten function

28.1.3 The flatMap function

28.2 For-comprehension

Summary

Answers to quick checks

sitemap