Scala Collections
Learn about Lists, Maps, Sets, and other Scala collections.
Immutable Collections
Scala encourages immutable collections by default:
import scala.collection.immutable._
// List
val numbers = List(1, 2, 3, 4, 5)
val doubled = numbers.map(_ * 2)
// Set
val uniqueNumbers = Set(1, 2, 3, 2, 1) // Becomes Set(1, 2, 3)
// Map
val ages = Map("Alice" -> 25, "Bob" -> 30)
val aliceAge = ages("Alice") // 25
Mutable Collections
When you need mutability, import mutable collections explicitly:
import scala.collection.mutable
// Mutable ListBuffer
val buffer = mutable.ListBuffer(1, 2, 3)
buffer += 4 // Adds element
buffer -= 2 // Removes element
// Mutable Set
val mutableSet = mutable.Set(1, 2, 3)
mutableSet += 4 // Adds element
mutableSet -= 2 // Removes element
// Mutable Map
val mutableMap = mutable.Map("a" -> 1, "b" -> 2)
mutableMap("c") = 3 // Adds new key-value pair
Common Collection Operations
Operation | Description | Example |
---|---|---|
map | Transform each element | List(1,2,3).map(_ * 2) → List(2,4,6) |
filter | Select elements that satisfy predicate | List(1,2,3).filter(_ > 1) → List(2,3) |
fold | Combine elements with binary operation | List(1,2,3).fold(0)(_ + _) → 6 |
flatMap | Map then flatten | List(1,2).flatMap(x ⇒ List(x,x)) → List(1,1,2,2) |
reduce | Combine elements without initial value | List(1,2,3).reduce(_ + _) → 6 |
groupBy | Group elements by key | List("a", "aa", "b").groupBy(_.length) → Map(1 → List("a", "b"), 2 → List("aa")) |
Collection Hierarchy
Scala collections follow a consistent hierarchy:
Traversable
├── Iterable
│ ├── Seq
│ │ ├── IndexedSeq (Vector, Array, String)
│ │ └── LinearSeq (List, Queue, Stack)
│ ├── Set
│ │ ├── SortedSet (TreeSet)
│ │ └── HashSet
│ └── Map
│ ├── SortedMap (TreeMap)
│ └── HashMap
Performance Characteristics
Collection | Operation | Time Complexity |
---|---|---|
List | head | O(1) |
List | tail | O(1) |
List | access by index | O(n) |
Vector | access by index | O(log32(n)) |
Set | contains | O(1) |
Map | lookup | O(1) |