How to iterate over a Hashmap in Kotlin?


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 upon MutableMap interface and it does that by implementing MutableMap interface of HashTable. Kotlin provides four types of constructor to define and manipulate HashMap.

  • HashMap() – It is the default constructor which helps us create an empty HashMap.

  • HashMap(initialCapacity: Int, loadFactor: Float = 0f) – It helps us create a HashMap using initial capacity; if it is not provided, then it will be ignored and it will act as default HashMap().

  • HashMap(initialCapacity: Int) – It helps us create a HashMap with the given capacity.

  • HashMap(original: Map <out K, V>) – It creates an instance of HashMap as specified in the Map.

Here, we will be using HashMap() constructor to create a HashMap and its corresponding Put() to populate the same with some key-value data. In this example, we will create a collection of "subject" which will hold the subject name and our personal preference number. We will iterate through this HashMap using different options available in the Kotlin library.

Iterate Using for() Loop

In conventional programming languages, we have the for() loop to traverse through any of the collection. In the following example, we will traverse through the Map using for() loop.

Example

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("C++" , 4);
   subject.put("SQL" , 5);

   //iterate through for loop
   println("---------iterate using for Loop------------
") for ((k, v) in subject) { println(" Subject Name -> $k and its preference -> $v") } println("

") }

Output

Once you execute the code, it will generate the following output −

$kotlinc -nowarn main.kt -include-runtime -d main.jar
$java -Xmx128M -Xms16M -jar main.jar

---------iterate using for Loop------------
Subject Name -> Java and its preference -> 1
Subject Name -> C++ and its preference -> 4
Subject Name -> Kotlin and its preference -> 2
Subject Name -> Python and its preference -> 3
Subject Name -> SQL and its preference -> 5

Iterate using ForEach() Loop

Besides for() loop, we can also use ForEach() to propagate through a collection. In the following example, we will traverse through the Map using forEach() loop.

Example

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("C++" , 4);
   subject.put("SQL" , 5);

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

") }

Output

Once you execute the code, it will produce the following output −

$kotlinc -nowarn main.kt -include-runtime -d main.jar
$java -Xmx128M -Xms16M -jar main.jar

------iterate using forEach Method---------
Subject Name -> Java and its preference -> 1
Subject Name -> C++ and its preference -> 4
Subject Name -> Kotlin and its preference -> 2
Subject Name -> Python and its preference -> 3
Subject Name -> SQL and its preference -> 5

Using iterator() Method

Apart from the above conventional ways of traversing a collection, the Kotlin standard library also provides a function called iterator() that we can use to access objects in a collection without exposing the value of the same. This is the most efficient way of accessing all the values of a collection. In the following example, we will traverse the Hashmap using the iterator() method.

Example

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("C++" , 4);
   subject.put("SQL" , 5);

   //using iterator() method
   println("-----------Using iterator() Method-----------
")    val i = subject.keys.iterator()    while (i.hasNext()) {       val key = i.next()       val value = subject[key]       println("Subject Name -> ${key} and its preference -> $value") } }

Output

Once you execute the code, it will generate the following output −

$kotlinc -nowarn main.kt -include-runtime -d main.jar
$java -Xmx128M -Xms16M -jar main.jar

-----------Using iterator() Method-----------
Subject Name -> Java and its preference -> 1
Subject Name -> C++ and its preference -> 4
Subject Name -> Kotlin and its preference -> 2
Subject Name -> Python and its preference -> 3
Subject Name -> SQL and its preference -> 5

Updated on: 27-Oct-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements