11.17. Traversing a Map
Problem
You want to iterate over the elements in a map.
Solution
There are several different ways to iterate over the elements in a map. Given a sample map:
val
ratings
=
Map
(
"Lady in the Water"
->
3.0
,
"Snakes on a Plane"
->
4.0
,
"You, Me and Dupree"
->
3.5
)
my preferred way to loop over all of the map elements is with this
for
loop syntax:
for
((
k
,
v
)
<-
ratings
)
println
(
s
"key: $k, value: $v"
)
Using a match expression with the foreach
method is also very
readable:
ratings
.
foreach
{
case
(
movie
,
rating
)
=>
println
(
s
"key: $movie, value: $rating"
)
}
The following approach shows how to use the Tuple
syntax to access the key and value
fields:
ratings
.
foreach
(
x
=>
println
(
s
"key: ${x._1}, value: ${x._2}"
))
If you just want to use the keys in the map, the keys
method returns an Iterable
you can use:
ratings
.
keys
.
foreach
((
movie
)
=>
println
(
movie
))
For simple examples like this, that expression can be reduced as follows:
ratings
.
keys
.
foreach
(
println
)
In the same way, use the values
method to iterate over the values in the map:
ratings
.
values
.
foreach
((
rating
)
=>
println
(
rating
))
Note: Those are not my movie ratings. They are taken from the book, Programming Collective Intelligence (O’Reilly), by Toby Segaran.
Operating on map values
If you want to traverse the map to perform an operation on its
values, the mapValues
method may be
a better solution. It lets you perform a function on each map value,
and returns the modified map:
scala> var x = collection.mutable.Map(1 -> "a", 2 -> "b")
x: scala.collection.mutable.Map[Int,String] ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.