欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > kotlin的函数forEach

kotlin的函数forEach

2025/5/15 8:34:32 来源:https://blog.csdn.net/LCY133/article/details/146322931  浏览:    关键词:kotlin的函数forEach

在 Kotlin 中,forEach 是一个高阶函数,用于遍历集合中的每个元素并对其执行指定的操作。它的核心特点是 简洁、函数式,适用于需要遍历集合且无需返回值的场景。以下是详细说明和示例:


一、基本用法

1️⃣ 遍历集合
val list = listOf("Apple", "Banana", "Orange")// 使用 lambda 表达式
list.forEach { fruit -> println(fruit) 
}// 简化为 `it`
list.forEach { println(it) }
2️⃣ 遍历数组
val array = arrayOf(1, 2, 3)
array.forEach { println(it) }
3️⃣ 遍历 Map
val map = mapOf("A" to 1, "B" to 2)// 遍历键值对(Pair)
map.forEach { (key, value) ->println("$key -> $value")
}// 或直接使用 `it.key` 和 `it.value`
map.forEach { println("${it.key}: ${it.value}") }

二、与 for 循环的区别

特性forEachfor 循环
语法函数式风格,通过 lambda 操作元素传统循环结构
控制流无法使用 break/continue支持 break/continue
return 行为默认从外层函数返回(需用标签控制)仅退出当前循环
适用场景简单的遍历操作需要复杂控制流或提前终止循环的场景
示例:return 的行为
fun testForEach() {listOf(1, 2, 3).forEach {if (it == 2) return  // 直接退出整个函数!println(it)}println("End") // 不会执行
}// 输出:1
使用标签控制 return
fun testForEachLabel() {listOf(1, 2, 3).forEach {if (it == 2) return@forEach  // 仅退出当前 lambdaprintln(it)}println("End") // 会执行
}// 输出:1, 3, End

三、高级用法

1️⃣ 带索引遍历(结合 withIndex
list.withIndex().forEach { (index, value) ->println("$index: $value")
}
2️⃣ 忽略参数(使用 _
list.forEachIndexed { index, _ ->println("Index $index") // 忽略元素值
}
3️⃣ 链式调用(结合其他高阶函数)
list.filter { it.length > 5 }.forEach { println(it) } // 先过滤再遍历

四、注意事项

  1. 避免副作用
    forEach 应仅用于遍历,不要在其中修改外部变量(除非必要)。

    // ❌ 不推荐:修改外部状态
    var count = 0
    list.forEach { count++ }// ✅ 推荐:使用 `count()` 函数
    val count = list.size
    
  2. 不要修改集合本身
    遍历时修改集合(如增删元素)可能导致 ConcurrentModificationException

  3. 性能考量
    对大数据量或性能敏感场景,优先使用 for 循环(性能略优)。


五、常见场景示例

1️⃣ 遍历并处理元素
val numbers = listOf(10, 20, 30)
numbers.forEach { val squared = it * itprintln(squared)
}
2️⃣ 遍历文件内容
File("data.txt").readLines().forEach { line ->println(line.trim())
}
3️⃣ 验证数据
data class User(val name: String, val age: Int)
val users = listOf(User("Alice", 30), User("Bob", 17))users.forEach { user ->require(user.age >= 18) { "${user.name} 未成年!" }
}

六、总结

核心作用:遍历集合元素并执行操作。
适用场景:简单遍历、无需返回值的操作。
替代方案:需要复杂控制流时用 for 循环;需要返回新集合时用 map/filter

通过 forEach 可以让代码更简洁,但需注意其局限性。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词