Home » Scala language

How to reverse keys and values in Scala Map

Here, we are going to learn how to reverse keys and values in Map in Scala programming language?
Submitted by Shivang Yadav, on April 20, 2020

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.

Program:

object myObject { 
	def main(args:Array[String]) { 
		val bikes = Map(1->"S1000RR" , 2->"R1", 3->"F4" ) 
        println("Inital 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.

Program:

object myObject { 
	def main(args:Array[String]) { 
		val bikes = Map(1->"S1000RR" , 2->"R1", 3->"F4", 4->"S1000RR" ) 
        println("Inital 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, 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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.