Chapter 14. Collections: Using Maps

Scala Map types are like the Java Map, Ruby 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, Recipes 14.3 and 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 Recipes 14.5 through 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

Problem

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.

Solution

For the times when you need a key/value pair data structure, Scala lets you create both immutable and mutable Map types.

Immutable map

To create an immutable map, you don’t need an import statement, just ...

Get Scala Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.