Introduction

In this section, we will explore two fundamental collection types in Scala: Sets and Maps. These collections are essential for managing groups of unique elements and key-value pairs, respectively. Understanding how to use Sets and Maps effectively will enhance your ability to handle data in a structured and efficient manner.

Sets

What is a Set?

A Set is a collection of unique elements. Unlike lists or arrays, sets do not allow duplicate values. Sets are useful when you need to ensure that a collection contains no duplicates.

Creating Sets

Scala provides mutable and immutable sets. By default, Scala uses immutable sets.

Immutable Set

val fruitSet = Set("Apple", "Banana", "Cherry")
println(fruitSet) // Output: Set(Apple, Banana, Cherry)

Mutable Set

import scala.collection.mutable

val mutableFruitSet = mutable.Set("Apple", "Banana", "Cherry")
mutableFruitSet += "Date"
println(mutableFruitSet) // Output: Set(Apple, Banana, Cherry, Date)

Common Set Operations

Operation Description Example Code
Adding Elements Add elements to a set val newSet = fruitSet + "Date"
Removing Elements Remove elements from a set val newSet = fruitSet - "Banana"
Union Combine two sets val combinedSet = fruitSet union Set("Date", "Elderberry")
Intersection Find common elements between two sets val commonSet = fruitSet intersect Set("Banana", "Date")
Difference Find elements in one set but not in another val diffSet = fruitSet diff Set("Banana", "Date")
Checking Membership Check if an element exists in a set val hasApple = fruitSet.contains("Apple")

Practical Example

val setA = Set(1, 2, 3, 4)
val setB = Set(3, 4, 5, 6)

val unionSet = setA union setB
println(unionSet) // Output: Set(1, 2, 3, 4, 5, 6)

val intersectSet = setA intersect setB
println(intersectSet) // Output: Set(3, 4)

val diffSet = setA diff setB
println(diffSet) // Output: Set(1, 2)

Maps

What is a Map?

A Map is a collection of key-value pairs. Each key in a map is unique, and it maps to exactly one value. Maps are useful for associating data, such as storing a dictionary of words and their definitions.

Creating Maps

Scala provides mutable and immutable maps. By default, Scala uses immutable maps.

Immutable Map

val fruitPrices = Map("Apple" -> 1.0, "Banana" -> 0.5, "Cherry" -> 2.0)
println(fruitPrices) // Output: Map(Apple -> 1.0, Banana -> 0.5, Cherry -> 2.0)

Mutable Map

import scala.collection.mutable

val mutableFruitPrices = mutable.Map("Apple" -> 1.0, "Banana" -> 0.5, "Cherry" -> 2.0)
mutableFruitPrices("Date") = 1.5
println(mutableFruitPrices) // Output: Map(Apple -> 1.0, Banana -> 0.5, Cherry -> 2.0, Date -> 1.5)

Common Map Operations

Operation Description Example Code
Adding Elements Add key-value pairs to a map val newMap = fruitPrices + ("Date" -> 1.5)
Removing Elements Remove key-value pairs from a map val newMap = fruitPrices - "Banana"
Accessing Values Retrieve the value associated with a key val applePrice = fruitPrices("Apple")
Checking Keys Check if a key exists in a map val hasApple = fruitPrices.contains("Apple")
Iterating Iterate over key-value pairs fruitPrices.foreach { case (key, value) => println(s"$key: $value") }

Practical Example

val fruitPrices = Map("Apple" -> 1.0, "Banana" -> 0.5, "Cherry" -> 2.0)

val updatedPrices = fruitPrices + ("Date" -> 1.5)
println(updatedPrices) // Output: Map(Apple -> 1.0, Banana -> 0.5, Cherry -> 2.0, Date -> 1.5)

val withoutBanana = updatedPrices - "Banana"
println(withoutBanana) // Output: Map(Apple -> 1.0, Cherry -> 2.0, Date -> 1.5)

val applePrice = updatedPrices("Apple")
println(s"Price of Apple: $$applePrice") // Output: Price of Apple: $1.0

updatedPrices.foreach { case (key, value) => println(s"$key: $$value") }
// Output:
// Apple: $1.0
// Banana: $0.5
// Cherry: $2.0
// Date: $1.5

Exercises

Exercise 1: Set Operations

  1. Create a set of integers from 1 to 5.
  2. Create another set of integers from 4 to 8.
  3. Find the union, intersection, and difference of these sets.

Solution

val set1 = Set(1, 2, 3, 4, 5)
val set2 = Set(4, 5, 6, 7, 8)

val unionSet = set1 union set2
println(unionSet) // Output: Set(1, 2, 3, 4, 5, 6, 7, 8)

val intersectSet = set1 intersect set2
println(intersectSet) // Output: Set(4, 5)

val diffSet = set1 diff set2
println(diffSet) // Output: Set(1, 2, 3)

Exercise 2: Map Operations

  1. Create a map of three fruits and their prices.
  2. Add a new fruit to the map.
  3. Remove one fruit from the map.
  4. Retrieve the price of one fruit and print it.

Solution

val fruitPrices = Map("Apple" -> 1.0, "Banana" -> 0.5, "Cherry" -> 2.0)

val updatedPrices = fruitPrices + ("Date" -> 1.5)
println(updatedPrices) // Output: Map(Apple -> 1.0, Banana -> 0.5, Cherry -> 2.0, Date -> 1.5)

val withoutBanana = updatedPrices - "Banana"
println(withoutBanana) // Output: Map(Apple -> 1.0, Cherry -> 2.0, Date -> 1.5)

val applePrice = updatedPrices("Apple")
println(s"Price of Apple: $$applePrice") // Output: Price of Apple: $1.0

Conclusion

In this section, we covered the basics of Sets and Maps in Scala. We learned how to create and manipulate these collections, perform common operations, and apply them in practical examples. Understanding Sets and Maps is crucial for managing unique elements and key-value pairs efficiently in your Scala programs. In the next section, we will delve into Tuples and Options, which provide additional ways to handle data in Scala.

© Copyright 2024. All rights reserved