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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.