Chapter 14. Collections: Using Maps
Map types are like the Java
Hash, or Python dictionary, in that they consist of key/value pairs, and the key values must be unique. Recipe 14.1 provides an introduction to the basics of creating and using immutable and mutable maps.
After that introduction to maps, Recipe 14.2 helps you choose a map implementation for the times you need to use special map features. Following that, Recipe 14.3 and Recipe 14.4 cover the processes of adding, updating, and removing elements in immutable and mutable maps, respectively.
If you’re coming to Scala from Java, one big difference with maps is that the default
Map in Scala is immutable, so if you’re not used to working with immutable collections, this can be a big surprise when you attempt to add, delete, or change elements in the map.
In addition to adding, removing, and replacing map elements, other common map tasks are working with their keys and values (shown in Recipe 14.5 through Recipe 14.8), as well as traversing (Recipe 14.9), sorting (Recipe 14.10), and filtering (Recipe 14.11) maps.
14.1 Creating and Using Maps
You want to create and use a
Map in a Scala application, i.e., a data structure that contains key/value pairs, like a Java map, Python dictionary, or Ruby hash.
For the times when you need a key/value pair data structure, Scala lets you create both immutable and mutable
To create an immutable map, you don’t need an