How to reverse a Map in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

Kotlin provides four types of constructors to define and manipulate a HashMap. In this article, we will see how we can reverse a map using Kotlin library function.

A Map is a collection where data is stored as a key-value pair and the corresponding key has to be unique.

A HashMap is a collection class based on MutableMap interface and it does that by implementing the MutableMap interface of HashTable.

Example − Reverse using Iterable associate()

In this example, we will create a HashMmap and we will reverse the same using associate(). In this method, we will be creating a new map and we will map the value to the key and the key with the value.

fun main(args: Array<String>) {
   var subject : HashMap<String, Int>
   = HashMap<String, Int> ();
   subject.put("Java" , 1);
   subject.put("Kotlin" , 2);
   subject.put("Python" , 3);
   subject.put("SQL" , 4);

   println(subject) // map before reversing

   // interchanging key and value pair
   val reversed = subject.entries.associate{(k,v)-> v to k}



On execution, it will generate the following output −

{Java=1, Kotlin=2, Python=3, SQL=4}
{1=Java, 2=Kotlin, 3=Python, 4=SQL}
Updated on 01-Mar-2022 11:41:15