34 Set

 

After reading this lesson, you will be able to

  • Define an unordered group of distinct values called Set
  • Add and remove items from Set
  • Manipulate a set’s elements using the map, flatten, and flatMap methods
  • Chain multiple Set instances using for-comprehension

In the previous unit, you have learned about List and the operations you can perform on it. In this lesson, you’ll discover the collection Set as an immutable representation of a group of elements. Sets and lists have many features in common and similar syntax, with a fundamental difference: the items of a set are unique and have no order. You’ll see how to create a set and add and remove elements from it. You’ll discover how to manipulate its items using the map, flatten, and flatMap operations. Finally, you’ll chain multiple instances of Set using for-comprehension. In the capstone, you’ll use sets to store the book loans of a library.

34.1 Creating a set

Suppose you are writing a program to track which topics a student has selected, and each of them must be unique.

Listing 34.1 The Student and Exam classes
case class Student(id: Int, name: String, topics: Set[String])   #1
 
val alice = Student(
  id = 1, 
  name = "Alice Abbott", 
  topics = Set("History", "Math")                                #2
)

34.2 Adding and removing elements

34.3 The map, flatten, and flatMap operations

34.3.1 The map function

34.3.2 The flatten function

34.3.3 The flatMap function

34.4 For-comprehension

Summary

Answers to quick checks