Immutable map: val scores = Map("Alice" -> 10, "Bob" -> 3).

Mutable map: val scores = scala.collection.mutable.Map("Alice" -> 10, "Bob" -> 3).

Maps are implemented as hash tables.

SortedMap is an immutable tree map.

Map is a collection of pairs. A pair is a group of two values. -> operator makes a pair so the value of "Alice" -> 10 is ("Alice", 10). So map can be defined as val scores = Map(("Alice", 10), ("Bob", 3)), too.

Get value from map

val bobScore = scores("Bob"). It will throw exception if key "bob" does not exist.

val bobScore = scores.get("Bob") returns an Option that can be None if key "bob" does not exist.

scores.contains("Bob") checks if Bob is in the map key.

scores.getOrElse("Bob", 0) returns value of Bob if found, 0 otherwise.

Update Map

scores("Fred") = 7. Only works on a mutable map.

Add multiple associations or update: scores += ("Bob" -> 10, "Fred" -> 7).

Remove an association: scores -= "Alice". Only remove the key.

You can create a new Map by modifying and immutable map using + (add or update) and -. Or make scores a var so that the new Map can be assigned to scores. Then += and -= can be used. It is NOT inefficient to use immutable map this way.

map -- map2 remove occurrences in map2 from map.

Map Iteration

for ((k, v) <- scores) process k and v

scores.keySet returns a Set of keys.

scores.keys and scores.values returns an Iterable that can be used in for loop.