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做的过程(k、v)
The magic here is that you can use pattern matching in a Scalaforloop. (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 thekeySetandvaluesmethods. Thevaluesmethod returns anIterablethat you can use in aforloop.
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) <-mapyield (v, k)