10.2. Choosing a Collection Class

Problem

You want to choose a Scala collection class to solve a particular problem.

Solution

There are three main categories of collection classes to choose from:

  • Sequence

  • Map

  • Set

A sequence is a linear collection of elements and may be indexed or linear (a linked list). A map contains a collection of key/value pairs, like a Java Map, Ruby Hash, or Python dictionary. A set is a collection that contains no duplicate elements.

In addition to these three main categories, there are other useful collection types, including Stack, Queue, and Range. There are a few other classes that act like collections, including tuples, enumerations, and the Option/Some/None and Try/Success/Failure classes.

Choosing a sequence

When choosing a sequence (a sequential collection of elements), you have two main decisions:

  • Should the sequence be indexed (like an array), allowing rapid access to any elements, or should it be implemented as a linked list?

  • Do you want a mutable or immutable collection?

As of Scala 2.10, the recommended, general-purpose, “go to” sequential collections for the combinations of mutable/immutable and indexed/linear are shown in Table 10-1.

Table 10-1. Scala’s general-purpose sequential collections

 

Immutable

Mutable

Indexed

Vector

ArrayBuffer

Linear (Linked lists)

List

ListBuffer

As an example of reading that table, if you want an immutable, indexed collection, in general you should use a Vector; if you want a mutable, indexed collection, use an ArrayBuffer (and so on). ...

Get Scala Cookbook 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.