11.19. Reversing Keys and Values
Problem
You want to reverse the contents of a map, so the values become the keys, and the keys become the values.
Solution
You can reverse the keys and values of a map with a for comprehension, being sure to assign the result to a new variable:
val
reverseMap
=
for
((
k
,
v
)
<-
map
)
yield
(
v
,
k
)
But be aware that values don’t have to be unique and keys must be,
so you might lose some content. As an example of this, reversing the
following map—where two values are $5
—results in one of the items being dropped
when the keys and values are reversed:
scala>val products = Map(
|"Breadsticks" -> "$5",
|"Pizza" -> "$10",
|"Wings" -> "$5"
|)
products: scala.collection.mutable.Map[String,String] = Map(Wings -> $5, Pizza -> $10, Breadsticks -> $5) scala>val reverseMap = for ((k,v) <- products) yield (v, k)
reverseMap: scala.collection.mutable.Map[String,String] = Map($5 -> Breadsticks, $10 -> Pizza)
As shown, the $5
wings were
lost when the values became the keys, because both the breadsticks and
the wings had the String
value
$5
.
See Also
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.