Home > Articles

This chapter is from the book

4.4 Iterating over Maps

The following amazingly simple loop iterates over all key/value pairs of a map:

for (k, v) <- map do process(k, v)

The magic here is that you can use pattern matching in a Scala for loop. (Chapter 14 has all the details.) That way, you get the key and value of each pair in the map without tedious method calls.

If for some reason you want to visit only the keys or values, use the keySet and values methods. The values method returns an Iterable that you can use in a for loop.

val scores = Map("Alice" -> 10, "Bob" -> 7, "Fred" -> 8, "Cindy" -> 7)
scores.keySet // Yields a set with elements "Alice", "Bob", "Fred", and "Cindy"
for v <- scores.values do println(v) // Prints 10 7 8 7

To invert a map—that is, switch keys and values—use

for (k, v) <- map yield (v, k)

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.