36 Map

 

After reading this lesson, you will be able to

  • Define a key-value structure, called Map
  • Add and remove entries to Map
  • Compute the union and difference of two Maps
  • Manipulate the elements of a key-value structure using the map and flatMap functions
  • Chain multiple instances using for-comprehension

In the previous lesson, you mastered the operations you can perform on a set. In this lesson, you’ll discover a new data structure called Map. In Scala, Map is an immutable data structure to store a set of keys, each of them associated with a value. The concept of mapping keys to values is not unique to the Scala language; some languages, such as Java, refer to it using the term hashmap; others, such as Python, call it dictionary. You’ll create an instance of Map and add and remove elements to it. You’ll merge and subtract the keys of two maps to create a new one. You’ll manipulate and transform its entries using the map and flatMap functions. You’ll also combine multiple values using for-comprehension. In the capstone, you’ll use Map to read the data from a CSV file.

36.1 Creating Map

Consider the program to track the students and their selected topics you developed in previous lessons. Imagine you want to modify it so that you can record the students registered for an exam session.

36.2 Adding and removing elements

36.3 Merge and remove multiple entries

36.4 The map and flatMap operations

36.4.1 The map function

36.4.2 The flatMap function

36.5 For-comprehension

Summary

Answers to quick checks