Kotlin –如何循环地图

向右看齐 2023-02-15 05:07 14阅读 0赞

在Kotlin中,您可以通过以下方式循环Map

  1. for循环

    val items = HashMap()

    1. items["A"] = 10
    2. items["B"] = 20
    3. for ((k, v) in items) {
    4. println("$k = $v")
    5. }
  2. forEach

    items.forEach {

    1. k, v ->
    2. println("$k = $v")
    3. }

1.对于循环

循环映射并通过键或值对其进行过滤。

  1. fun main(args: Array<String>) {
  2. val items = HashMap<String, Int>()
  3. items["A"] = 10
  4. items["B"] = 20
  5. items["C"] = 30
  6. println("-- Example 1 -- \n $items");
  7. //for loop
  8. println("\n-- Example 1.1 -- ");
  9. for ((k, v) in items) {
  10. println("$k = $v")
  11. }
  12. //for loop + lambdas filter
  13. println("\n-- Example 1.2 --");
  14. for ((k, v) in items) {
  15. if (k == "C")
  16. println("Find by key 'C' : $k = $v")
  17. }
  18. //Actually, you can filter key like this
  19. println("\n-- Example 1.3 -- ");
  20. val filteredItems = items.filterKeys { it == "A" || it == "C" }
  21. println("Find by key == A or C : $filteredItems")
  22. //Or filter value like this
  23. println("\n-- Example 1.4 --");
  24. val filterItems2 = items.filterValues { it <= 20 }
  25. println("Find by value <=20 : $filterItems2")
  26. //Or just filters
  27. println("\n-- Example 1.5 --");
  28. val filterItems3 = items.filter { it.key == "B" && it.value == 20 }
  29. println("Find by key == 'B' and value == 20 : $filterItems3")
  30. }

输出量

  1. -- Example 1 --
  2. {A=10, B=20, C=30}
  3. -- Example 1.1 --
  4. A = 10
  5. B = 20
  6. C = 30
  7. -- Example 1.2 --
  8. Find by key 'C' : C = 30
  9. -- Example 1.3 --
  10. Find by key == A or C : {A=10, C=30}
  11. -- Example 1.4 --
  12. Find by value <=20 : {A=10, B=20}
  13. -- Example 1.5 --
  14. Find by key = 'B' and value ==20 : {B=20}

2. forEach

  1. fun main(args: Array<String>) {
  2. val items2 = hashMapOf("A" to 10, "B" to 20, "C" to 30)
  3. items2["D"] = 40
  4. // foreach example
  5. println("\n-- Example 2.1 --");
  6. items2.forEach { k, v ->
  7. println("$k = $v")
  8. }
  9. // foreach + filter
  10. println("\n-- Example 2.1 --");
  11. items2.forEach { k, v ->
  12. if (v == 10) {
  13. println("$k = $v")
  14. }
  15. }
  16. // using the special 'it' like this
  17. println("\n-- Example 2.2 --");
  18. items2.forEach { println("key : ${it.key}, value : ${it.value}") }
  19. }

输出量

  1. -- Example 2.1 --
  2. A = 10
  3. B = 20
  4. C = 30
  5. D = 40
  6. -- Example 2.1 --
  7. A = 10
  8. -- Example 2.2 --
  9. key : A, value : 10
  10. key : B, value : 20
  11. key : C, value : 30
  12. key : D, value : 40

参考文献

  1. Kotlin地图
  2. Kotlin过滤器按键
  3. Kotlin forEach

标签: 循环 foreach Kotlin 地图的 过滤器

翻译自: https://mkyong.com/kotlin/kotlin-how-to-loop-a-map/

发表评论

表情:
评论列表 (有 0 条评论,14人围观)

还没有评论,来说两句吧...

相关阅读