Scala Collections - Maps

Question Click to View Answer

What does the following code print?

val simple = Map("r" -> "red", "g" -> "green")
println(simple("g"))

green is printed.

A map is a collection of key / value pairs as tuples. In the simple map, "r" / "g" are keys and "red" / "green" are values.

What does the following code print?

val airport = Map("jfk" -> "new york", "lga" -> "new york")
println(airport("lax"))

This code throws a java.util.NoSuchElementException.

The airport map does not have an element with a lax key, so an error is thrown.

What does the following code print?

val player = Map("skates" -> "bauer", "stick" -> "nike")
println(player.contains("stick"))

true is printed.

The player map contains the stick key. player.contains("helmet") returns false because the "helmet" key is not included in the map.

What does the following code print?

val cool = Map("a" -> "aaa", "b" -> "bbb", "a" -> "ccc")
println(cool("a"))

ccc is printed.

The cool map has two keys that start with "a". The first duplicate key / value pair is ignored and the map is defined as follows: cool: scala.collection.immutable.Map[String,String] = Map(a -> ccc, b -> bbb).

What does the following code print?

val numbers = Map(1 -> "one", 2 -> "two", 3 -> "three")
val odds = numbers - 2
println(odds)

Map(1 -> one, 3 -> three) is printed.

The numbers map includes three key / value pairs. The odds map is equal to the numbers map, minus one of the key / value pairs.

What does the following code print?

val some = Map(23 -> "twenty three")
val more = some + (8 -> "eight")
println(more)

Map(23 -> twenty three, 8 -> eight) is printed.

Notice that the some map is not changed. Scala maps are immutable and the some map cannot be changed. A separate more map is created to add key / value pair to the some map.

What does the following code print?

val shoes = collection.mutable.Map("jordan" -> "nike")
shoes += ("griffey" -> "nike")
println(shoes)

Map(griffey -> nike, jordan -> nike) is printed.

shoes is a mutable map, so a key / value can be paired to the map. Maps are immutable by default (collection.immutable.Map is used by default), but mutable maps can be constructed as well.

What does the following code print?

val animals = Map("fox" -> "sly")
animals += ("cheetah" -> "fast")
println(animals)

This code throws an error. The animals map is immutable (collection.immutable.Map is used by default), so a key / value pair cannot be added to the map. If a mutable map was used (collection.mutable.Map), then this code would have worked.

What does the following code print?

val birthYears = Map("lebron" -> 1984, "jordan" -> 1963)
val yearSum = birthYears.foldLeft(0) { case (memo: Int, (name: String, year: Int)) =>
  memo + year
}
println(yearSum / birthYears.size)

1973 is printed.

The code iterates over the birthYears map and sums all of the years. It prints the years divided by the number of key / value pairs in the map.