This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one the smallest recipes, Recipe 11.20, “How to Reverse Keys and Values in a Scala Map”
You want to reverse the contents of a Scala
Map, so the values become the keys, and the keys become the values.
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.00 — 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.
- Recipe 3.4, “Creating a For Comprehension (for/yield Combination)”
- Recipe 10.13, “Transforming One Collection to Another with for/yield”
The Scala Cookbook
This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:
You can find the Scala Cookbook at these locations: