Home »
Scala
How to reverse keys and values in Scala Map
By IncludeHelp Last updated : November 15, 2024
Scala Map
A Map is a data structure that stores data as key: value pair.
Syntax
Map(key->value, key->value)
Reversing Keys and Values in Map
Here, we will see a program to reverse keys and values in Scala Map. We will reverse the values to keys and the keys to pairs.
So, before this, we will have to make sure that both keys and values of the initial map are unique to avoid errors.
Example
object myObject {
def main(args: Array[String]): Unit = {
val bikes = Map(1 -> "S1000RR", 2 -> "R1", 3 -> "F4")
println("Initial map: " + bikes)
val reverse = for ((a, b) <- bikes) yield (b, a)
println("Reversed map: " + reverse)
}
}
Output
Inital map: Map(1 -> S1000RR, 2 -> R1, 3 -> F4)
Reversed map: Map(S1000RR -> 1, R1 -> 2, F4 -> 3)
Explanation
Here, we have declared a map and then reversed its values. In the reverse variable, we have inserted value that is reverse of each pair of the original map, the yield methods take the (key, value) pair and returns (value, key) pair to the reverse map.
What if values are not unique?
There is a thing that is needed to be considered is both key-value pairs should be unique. But if we insert a duplicate in value, in the reverse map this will delete that pair.
Example
object myObject {
def main(args: Array[String]): Unit = {
val bikes = Map(1 -> "S1000RR", 2 -> "R1", 3 -> "F4", 4 -> "S1000RR")
println("Initial map: " + bikes)
// Reversing the map by converting it to a list and swapping keys and values
val reverse = bikes.toList.map{ case (a, b) => (b, a) }
println("Reversed map: " + reverse)
}
}
Output
Inital map: Map(1 -> S1000RR, 2 -> R1, 3 -> F4, 4 -> S1000RR)
Reversed map: Map(S1000RR -> 4, R1 -> 2, F4 -> 3)
So, the code runs properly but the reverse will delete the pair 4->S100RR to make all the keys of reverse map unique.