Main Tutorials

Kotlin – How to Loop a Map

In Kotlin, you can loop a Map via the following ways:

1. for loop


	val items = HashMap<String, Int>()
	items["A"] = 10
	items["B"] = 20
	
	for ((k, v) in items) {
		println("$k = $v")
	}

2. forEach


	items.forEach { 
		k, v -> 
			println("$k = $v")
	}

1. For Loop

Loop a Map and filter it by keys or values.


fun main(args: Array<String>) {

    val items = HashMap<String, Int>()
    items["A"] = 10
    items["B"] = 20
    items["C"] = 30

    println("-- Example 1 -- \n $items");

    //for loop
    println("\n-- Example 1.1 -- ");
    for ((k, v) in items) {
        println("$k = $v")
    }

    //for loop + lambdas filter
    println("\n-- Example 1.2 --");
    for ((k, v) in items) {
        if (k == "C")
            println("Find by key 'C' : $k = $v")
    }

    //Actually, you can filter key like this
    println("\n-- Example 1.3 -- ");
    val filteredItems = items.filterKeys { it == "A" || it == "C" }
    println("Find by key == A or C : $filteredItems")

    //Or filter value like this
    println("\n-- Example 1.4 --");
    val filterItems2 = items.filterValues { it <= 20 }
    println("Find by value <=20 : $filterItems2")

    //Or just filters
    println("\n-- Example 1.5 --");
    val filterItems3 = items.filter { it.key == "B" && it.value == 20 }
    println("Find by key == 'B' and value == 20 : $filterItems3")

}

Output


-- Example 1 -- 
 {A=10, B=20, C=30}

-- Example 1.1 -- 
A = 10
B = 20
C = 30

-- Example 1.2 --
Find by key 'C' : C = 30

-- Example 1.3 -- 
Find by key == A or C : {A=10, C=30}

-- Example 1.4 --
Find by value <=20 : {A=10, B=20}

-- Example 1.5 --
Find by key = 'B' and value ==20 : {B=20}

2. forEach


fun main(args: Array<String>) {

    val items2 = hashMapOf("A" to 10, "B" to 20, "C" to 30)
    items2["D"] = 40

    // foreach example
    println("\n-- Example 2.1 --");
    items2.forEach { k, v ->
        println("$k = $v")
    }

    // foreach + filter
    println("\n-- Example 2.1 --");
    items2.forEach { k, v ->
        if (v == 10) {
            println("$k = $v")
        }
    }

    // using the special 'it' like this
    println("\n-- Example 2.2 --");
    items2.forEach { println("key : ${it.key}, value : ${it.value}") }

}

Output


-- Example 2.1 --
A = 10
B = 20
C = 30
D = 40

-- Example 2.1 --
A = 10

-- Example 2.2 --
key : A, value : 10
key : B, value : 20
key : C, value : 30
key : D, value : 40

References

  1. Kotlin Map
  2. Kotlin filterKeys
  3. Kotlin forEach

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
gerogie
5 years ago

nice

Yong
5 years ago
Reply to  gerogie

Yes indeed!

ddfds
5 years ago
Reply to  Yong

amaging!