How to iterate over a HashMap in Kotlin
How to iterate over a HashMap in Kotlin.
Here's a detailed step-by-step tutorial on how to iterate over a HashMap in Kotlin:
Step 1: Create a HashMap
To begin, you need to create a HashMap in Kotlin. The HashMap is a collection that stores key-value pairs. You can define a HashMap using the mutableMapOf() function. For example:
val hashMap = mutableMapOf<String, Int>()
Here, we have created a HashMap named hashMap that stores keys of type String and values of type Int.
Step 2: Add elements to the HashMap
Next, you can add elements to the HashMap using the put() function. The put() function takes two arguments: the key and the value. For example:
hashMap.put("Apple", 10)
hashMap.put("Orange", 15)
hashMap.put("Banana", 20)
Here, we have added three key-value pairs to the HashMap.
Step 3: Iterate over the HashMap using for loop
To iterate over the HashMap, you can use a for loop in Kotlin. The for loop iterates over each key in the HashMap, and you can access the corresponding value using the key. For example:
for ((key, value) in hashMap) {
println("Key: $key, Value: $value")
}
This code will iterate over each key-value pair in the HashMap and print the key and value.
Step 4: Iterate over the HashMap using iterator()
Alternatively, you can use the iterator() function to iterate over the HashMap. The iterator() function returns an iterator that allows you to loop over the keys and values. Here's an example:
val iterator = hashMap.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
val key = entry.key
val value = entry.value
println("Key: $key, Value: $value")
}
In this code, we get an iterator from the HashMap and use a while loop to iterate over the keys and values. We access the key and value using the key and value properties of the iterator's entry.
Step 5: Iterate over the HashMap keys or values only
If you only need to iterate over the keys or values of the HashMap, you can use the keys or values properties. Here's an example:
// Iterate over keys
for (key in hashMap.keys) {
println("Key: $key")
}
// Iterate over values
for (value in hashMap.values) {
println("Value: $value")
}
In these examples, we use a for loop to iterate over the keys or values of the HashMap. We can access each key or value directly without the need for a separate iterator.
That's it! You have now learned how to iterate over a HashMap in Kotlin. You can use the for loop, iterator(), keys, or values properties depending on your specific requirements.