Kotlin How to Loop a Map

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

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

上一篇: Java Bubble sort example
下一篇: Intellij IDEA System.out.println shortcut
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号