Kotlin中遍历集合的方法

在 Kotlin 中,遍历 MutableList 有多种方式,可根据需求选择合适的方法,以下是常用遍历方式及示例:

1. for 循环遍历(最常用)

直接通过 for-in 循环遍历 MutableList,语法简洁,适用于大多数场景。

kotlin 复制代码
val mutableList = mutableListOf("A", "B", "C")

// 遍历元素
for (item in mutableList) {
    println(item) // 输出:A、B、C
}

// 遍历索引和元素(withIndex())
for ((index, item) in mutableList.withIndex()) {
    println("索引 $index:$item") // 输出:索引 0:A、索引 1:B、索引 2:C
}

2. 迭代器遍历(Iterator)

通过 iterator() 获取迭代器,手动控制遍历过程,支持在遍历中安全删除元素。

kotlin 复制代码
val mutableList = mutableListOf("A", "B", "C")
val iterator = mutableList.iterator()

while (iterator.hasNext()) {
    val item = iterator.next()
    println(item) // 输出:A、B、C

    // 遍历中删除元素(安全操作)
    if (item == "B") {
        iterator.remove() // 删除 "B",不会触发 ConcurrentModificationException
    }
}

println(mutableList) // 输出:[A, C]

3. forEach 遍历(函数式风格)

使用 forEach 扩展函数,简洁高效,适合不需要中断遍历的场景。

kotlin 复制代码
val mutableList = mutableListOf("A", "B", "C")

// 基本遍历
mutableList.forEach { item ->
    println(item) // 输出:A、B、C
}

// 简化写法(单个参数可省略 ->)
mutableList.forEach {
    println(it) // 输出:A、B、C
}

// 带索引的 forEachIndexed
mutableList.forEachIndexed { index, item ->
    println("索引 $index:$item") // 输出:索引 0:A、索引 1:B、索引 2:C
}

4. 遍历并修改元素

如果需要在遍历中修改元素,可通过索引遍历或 withIndex() 实现。

kotlin 复制代码
val mutableList = mutableListOf(1, 2, 3)

// 通过索引遍历修改
for (i in mutableList.indices) {
    mutableList[i] *= 2 // 元素翻倍
}

println(mutableList) // 输出:[2, 4, 6]

// 或用 withIndex() 修改
val list = mutableListOf("X", "Y", "Z")
for ((index, item) in list.withIndex()) {
    list[index] = item.lowercase() // 转为小写
}

println(list) // 输出:[x, y, z]

5. 其他遍历方式

  • listIterator() :双向迭代器,支持向前 / 向后遍历,适合复杂场景。

    kotlin 复制代码
    val mutableList = mutableListOf("A", "B", "C")
    val listIterator = mutableList.listIterator(mutableList.size) // 从末尾开始
    
    while (listIterator.hasPrevious()) {
        println(listIterator.previous()) // 输出:C、B、A
    }
  • for 循环 + 索引范围:手动控制索引范围,灵活但需注意边界。

    kotlin 复制代码
    val mutableList = mutableListOf("A", "B", "C")
    for (i in 0 until mutableList.size) {
        println(mutableList[i]) // 输出:A、B、C
    }

总结

  • 简单遍历 :优先用 for-inforEach
  • 需要索引 :用 withIndex()forEachIndexed
  • 遍历中删除 :必须用 Iteratoriterator()listIterator())。
  • 函数式风格 :用 forEachforEachIndexed

根据具体场景选择最合适的遍历方式即可。

相关推荐
IT_陈寒11 分钟前
Vue3性能优化实战:这5个技巧让我的应用加载速度提升了40%
前端·人工智能·后端
长征coder12 分钟前
SpringCloud服务优雅下线LoadBalancer 缓存配置方案
java·后端·spring
ForteScarlet25 分钟前
Kotlin 2.3.0 现已发布!又有什么好东西?
android·开发语言·后端·ios·kotlin
Json____26 分钟前
springboot框架对接物联网,配置TCP协议依赖,与设备通信,让TCP变的如此简单
java·spring boot·后端·tcp/ip
程序员阿明28 分钟前
spring boot 3集成spring security6
spring boot·后端·spring
后端小张28 分钟前
【JAVA 进阶】深入拆解SpringBoot自动配置:从原理到实战的完整指南
java·开发语言·spring boot·后端·spring·spring cloud·springboot
草莓熊Lotso31 分钟前
C++11 核心进阶:引用折叠、完美转发与可变参数模板实战
开发语言·c++·人工智能·经验分享·后端·visualstudio·gitee
Q_Q51100828533 分钟前
小程序springBoot新农村综合风貌旅游展示平台
vue.js·spring boot·后端
风象南34 分钟前
Docker 容器实现按顺序启动
后端
BingoGo37 分钟前
10 个强大且值得掌握的 Linux 命令
后端