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()
}

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete