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.
val reverseMap = for ((k,v) <- map) yield (v, k)
Below is the example to reverse keys and values in Scala Map.
Map(geeks -> 3, for -> 4, cs -> 2)
Map(30 -> Ajay, 20 -> Bhavesh, 50 -> Charlie)
- How to get all the keys from a Scala map
- Scala Map keys() method with example
- Scala SortedMap keys() method with example
- Scala sum Map values
- How to get all the values from a Scala map
- Scala Product Map Values
- How to reverse a list in scala
- Scala Queue reverse() method with example
- Scala Stack reverse() method with example
- Scala Tutorial – Learn Scala with Step By Step Guide
- Scala Map
- Scala | Either
- Set in Scala | Set-1
- Set in Scala | Set-2
- Scala Map min() method with example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.