kotlin中遍历数组的几种方式

49 阅读1分钟

在 Kotlin 中遍历数组有多种方式,灵活适用于不同场景,以下是最常用的方法:

1. for-in 循环(最常用)

直接遍历数组中的每个元素,简洁直观:

kotlin

val array = arrayOf(1, 2, 3, 4, 5)

// 遍历元素
for (num in array) {
    println(num) // 依次输出 1, 2, 3, 4, 5
}

2. 遍历索引 + 元素(withIndex ())

需要同时获取元素的索引和值时,使用 withIndex()

kotlin

val array = arrayOf("a", "b", "c")

for ((index, value) in array.withIndex()) {
    println("索引 $index: $value") 
    // 输出:
    // 索引 0: a
    // 索引 1: b
    // 索引 2: c
}

3. 通过索引范围遍历

利用数组的 indices 属性(返回索引范围),按索引访问元素:

kotlin

val array = arrayOf(" Kotlin ", " Java ", " Python ")

// indices 等价于 0 until array.size
for (i in array.indices) {
    println("第 $i 个元素:${array[i].trim()}") 
}

4. forEach 高阶函数(函数式风格)

使用 forEach 方法,支持 Lambda 表达式,适合简洁的遍历逻辑:

kotlin

val array = intArrayOf(10, 20, 30)

// 遍历元素
array.forEach { println(it * 2) } // 输出 20, 40, 60

// 遍历索引 + 元素(forEachIndexed)
array.forEachIndexed { index, value ->
    println("索引 $index: $value") 
}

5. 迭代器(Iterator)

手动获取迭代器遍历(较少直接使用,多用于底层逻辑):

kotlin

val array = arrayOf("apple", "banana")
val iterator = array.iterator()

while (iterator.hasNext()) {
    println(iterator.next()) // 输出 apple, banana
}

总结

  • 简单遍历元素:优先用 for-in 或 forEach
  • 需要索引:用 withIndex() 或 forEachIndexed
  • 函数式编程场景:推荐 forEach 系列方法

这些方式适用于所有 Kotlin 数组类型(如 Array<T>IntArrayStringArray 等),且与 Java 集合的遍历风格兼容,学习成本低。