1. 概述
在本篇教程中,我们将学习几种在 Kotlin 中通过索引遍历集合的不同方法。
2. 仅使用索引遍历
在 Kotlin 中,如果只想通过索引遍历集合,可以使用集合的 indices 扩展属性。
示例代码如下:
val colors = listOf("Red", "Green", "Blue")
for (i in colors.indices) {
println(colors[i])
}
indices
属性会返回集合中所有有效索引组成的范围(Range),适用于所有集合类型,包括数组:
val colorArray = arrayOf("Red", "Green", "Blue")
for (i in colorArray.indices) {
println(colorArray[i])
}
当然,也可以手动构造一个范围来实现同样的功能:
for (i in 0 until colors.size) {
println(colors[i])
}
或者使用更紧凑的写法:
(0 until colors.size).forEach { println(colors[it]) }
这种方式虽然也能实现功能,但可读性略差。✅ 推荐优先使用 indices
扩展属性。
3. 同时获取索引与值
如果需要同时获取索引和元素值,可以使用 forEachIndexed()
扩展函数。
语法如下:
colors.forEachIndexed { i, v ->
println("The value for index $i is $v")
}
该函数的 Lambda 表达式接受两个参数:第一个是索引,第二个是元素值。
另外,也可以使用 withIndex()
函数配合 for
循环实现类似效果:
for (indexedValue in colors.withIndex()) {
println("The value for index ${indexedValue.index} is ${indexedValue.value}")
}
withIndex()
返回的是 IndexedValue
类型的集合。由于它是一个 data class,我们可以使用解构语法更优雅地处理:
for ((i, v) in colors.withIndex()) {
println("The value for index $i is $v")
}
✅ 使用解构语法是更推荐的方式,简洁又清晰。
此外,如果需要根据索引或值进行过滤操作,可以使用 filterIndexed()
函数。
例如,保留索引为偶数的元素:
colors.filterIndexed { i, v -> i % 2 == 0 }
同样地,如果不需要元素值,可以用 _
忽略:
colors.filterIndexed { i, _ -> i % 2 == 0 }
4. 小结
本篇教程我们学习了几种 Kotlin 中通过索引遍历集合的方法,包括:
- 仅使用索引遍历:
indices
、0 until collection.size
- 同时获取索引和值:
forEachIndexed()
、withIndex()
- 带过滤的索引遍历:
filterIndexed()
- 使用解构语法提升可读性
这些方法覆盖了大多数集合遍历场景,也展示了 Kotlin 中一些优雅的语法特性,比如解构声明。
如需查看完整示例代码,欢迎访问 GitHub 项目。