Iterate over the Map, List, and Set in Kotlin!How?
Hello everyone, Today we will learn how to operate over Map, List, and Set in Kotlin.
In Kotlin, we can loop a Map in the following ways:
1. Using for loop
2. Using forEach
3. Using Iterator
Example:
fun main(args : Array<String>) {
val items = HashMap<String, String>()
items["1"] = "JAVA"
items["2"] = "KOTLIN"
items["3"] = "GO"
items["3"] = "PYTHON"
//for loop example
println("\n-- Example 1.1 -- ");
for ((k, v) in items) {
println("$k = $v")
}
// forEach example
println("\n-- Example 1.2 --");
items.forEach { (k, v) ->
println("$k = $v")
}
//Iterator example
println("\n-- Example 1.3 --");
val itr = items.keys.iterator()
while (itr.hasNext()) {
val key = itr.next()
val value = items[key]
println("${key}=$value")
}
}
In Kotlin, we can loop a List in the following ways:
1.Using forEach() method
2.Using for loop
3.Using forEachIndexed() method
4.Using a ListIterator and a while loop
Example:
fun main(args: Array<String>) {
val languages = listOf("JAVA", "KOTLIN", "GO", "PYTHON")
// using forEach() method
languages.forEach { e -> print("$e ") }
println()
// using for loop
for (language in languages) {
print("$language ")
}
println()
// using forEachIndexed() method
languages.forEachIndexed({ i, e -> println("languages[$i] = $e") })
// using a ListIterator and a while loop
val it: ListIterator<String> = languages.listIterator()
while (it.hasNext()) {
val e = it.next()
print("$e ")
}
println()
}In Kotlin, we can loop a Set in the following ways:
1.Using forEach() method
2.Using for loop
3.Using forEachIndexed() method
4.Using a Iterator and a while loop
Example:
package com.knf.dev.config
fun main(args: Array<String>) {
val languages = setOf("JAVA", "KOTLIN", "GO", "PYTHON")
// using forEach() method
languages.forEach { e -> print("$e ") }
println()
// using for loop
for (language in languages) {
print("$language ")
}
println()
// using forEachIndexed() method
languages.forEachIndexed({ i, e -> println("languages[$i] = $e") })
// using a Iterator and a while loop
val it = languages.iterator()
while (it.hasNext()) {
println(it.next())
}
println()
}
More Kotlin practice:
- Kotlin +Spring Boot + Mongo DB + Vue.js CRUD
- Kotlin-Spring Boot-Thymeleaf-JPA-CRUD
- Angular 10 + Kotlin +Spring Boot + Mongo DB CRUD
- Kotlin + Spring Boot + React JS + MongoDB CRUD
- Build REST API's with Kotlin, Spring, and MongoDB
- Build REST API's with Kotlin, Spring, Spring Data JPA, and RDBMS
- Kotlin + Spring Boot + OpenCSV Export Data to CSV Example
- Kotlin + Spring Boot + Apache Commons Export Data to CSV Example
- WebSocket - Kotlin - Spring boot web application example
- Kotlin: RSA + AES a double layer security system
- Kotlin hashing - Using MD5, SHA-1, SHA-256, SHA-384, SHA-512, and PBKDF2
- Kotlin- AES, RSA, 3DES Encryption and Decryption with example
- Iterate over the Map, List, and Set in Kotlin! How?
- Kotlin Programming in Visual Studio Code IDE [Ubuntu]
- Kotlin - RSA Encryption and Decryption with example