VOOZH about

URL: https://www.geeksforgeeks.org/scala/how-to-reverse-keys-and-values-in-scala-map/

⇱ How to Reverse keys and values in Scala Map - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Reverse keys and values in Scala Map

Last Updated : 12 Jul, 2025
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: Output:
Map(geeks -> 3, for -> 4, cs -> 2)
Example #2: Output:
Map(30 -> Ajay, 20 -> Bhavesh, 50 -> Charlie)
Comment
Article Tags:

Explore