How to work with Maps in Kotlin?


A Map is a collection where data is stored as a key-value pair and the corresponding keys have to be unique. A HashMap is a collection class based on MutableMap interface and it does that by implementing the MutableMap interface of HashTable.

Kotlin provides four types of constructors to define and manipulate a HashMap.

Example – Map Creation and Iteration in Kotlin

In this example, we will be creating a Map called "subject" and we will be iterating through it.

fun main(args: Array<String>) {

   // Declare HashMap
   var subject : HashMap<String, Int>
      = HashMap<String, Int> ();

   // Assigning value to HashMap
   subject.put("Java" , 1);
   subject.put("Kotlin" , 2);
   subject.put("Python" , 3);
   subject.put("SQL" , 4);

   // iterate using forEach
   println("------iterate using forEach Method---------
")    subject.forEach { (k, v) ->       println(" Subject Name -> $k and its preference -> $v")    } }

Output

It will produce the following output −

------iterate using forEach Method---------

Subject Name -> Java and its preference -> 1
Subject Name -> Kotlin and its preference -> 2
Subject Name -> Python and its preference -> 3
Subject Name -> SQL and its preference -> 4

Example – Removing a value from a Map in Kotlin

In order to remove a value from a Map, we can use the remove() function.

fun main(args: Array<String>) {

   // Declare the HashMap
   var subject : HashMap<String, Int>
      = HashMap<String, Int> ();

   // Assigning value to HashMap
   subject.put("Java" , 1);
   subject.put("Kotlin" , 2);
   subject.put("Python" , 3);
   subject.put("SQL" , 4);

   // Remove
   subject.remove("SQL",4)

   // iterate using forEach
   println("------iterate using forEach Method---------
")    subject.forEach { (k, v) ->       println(" Subject Name -> $k and its preference -> $v")    } }

Output

It will produce the following output −

------iterate using forEach Method---------

Subject Name -> Java and its preference -> 1
Subject Name -> Kotlin and its preference -> 2
Subject Name -> Python and its preference -> 3

Updated on: 16-Mar-2022

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements