How to Reverse keys and values in Scala Map

In Scala, Map is same as dictionary which holds key:value pairs. In this article, we will learn how to reverse the keys and values in given Map in Scala. After reversing the pairs, keys will become values and values will become keys. We can reverse the keys and values of a map with a Scala for-comprehension. Keys should be unique for reverse these values otherwise we can lose some content.
Syntax:

val reverseMap = for ((k,v) <- map) yield (v, k)

Below is the example to reverse keys and values in Scala Map.

Example #1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to reverse keys and values
  
// Creating object 
object GfG 
  
    // Main method 
    def main(args:Array[String]) 
    
      
        // Creating a map 
        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs"
          
        // reversing key:value pairs 
        val reverse = for ((k, v) <- m1) yield (v, k)
  
        // Displays output 
        println(reverse) 
      
    

chevron_right


Output:

Map(geeks -> 3, for -> 4, cs -> 2)

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to reverse keys and values
  
// Creating object 
object GfG 
  
    // Main method 
    def main(args:Array[String]) 
    
      
        // Creating a map 
        val mapIm = Map("Ajay" -> 30
                        "Bhavesh" -> 20
                        "Charlie" -> 50
          
        // Applying keySet method 
        val reverse = for ((k, v) <- mapIm) yield (v, k)
  
        // Displays output 
        println(reverse) 
      
    

chevron_right


Output:

Map(30 -> Ajay, 20 -> Bhavesh, 50 -> Charlie)


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.