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

Spring boot video streaming example-HTML5

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

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example