kotlin的函數(shù)forEach示例詳解
在 Kotlin 中,forEach 是一個高階函數(shù),用于遍歷集合中的每個元素并對其執(zhí)行指定的操作。它的核心特點是 簡潔、函數(shù)式,適用于需要遍歷集合且無需返回值的場景。以下是詳細說明和示例:
一、基本用法
1?? 遍歷集合
val list = listOf("Apple", "Banana", "Orange")
// 使用 lambda 表達式
list.forEach { fruit ->
println(fruit)
}
// 簡化為 `it`
list.forEach { println(it) }2?? 遍歷數(shù)組
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 循環(huán)的區(qū)別
| 特性 | forEach | for 循環(huán) |
|---|---|---|
| 語法 | 函數(shù)式風格,通過 lambda 操作元素 | 傳統(tǒng)循環(huán)結(jié)構(gòu) |
| 控制流 | 無法使用 break/continue | 支持 break/continue |
return 行為 | 默認從外層函數(shù)返回(需用標簽控制) | 僅退出當前循環(huán) |
| 適用場景 | 簡單的遍歷操作 | 需要復雜控制流或提前終止循環(huán)的場景 |
示例:return 的行為
fun testForEach() {
listOf(1, 2, 3).forEach {
if (it == 2) return // 直接退出整個函數(shù)!
println(it)
}
println("End") // 不會執(zhí)行
}
// 輸出:1使用標簽控制 return
fun testForEachLabel() {
listOf(1, 2, 3).forEach {
if (it == 2) return@forEach // 僅退出當前 lambda
println(it)
}
println("End") // 會執(zhí)行
}
// 輸出:1, 3, End三、高級用法
1?? 帶索引遍歷(結(jié)合 withIndex)
list.withIndex().forEach { (index, value) ->
println("$index: $value")
}2?? 忽略參數(shù)(使用 _)
list.forEachIndexed { index, _ ->
println("Index $index") // 忽略元素值
}3?? 鏈式調(diào)用(結(jié)合其他高階函數(shù))
list.filter { it.length > 5 }
.forEach { println(it) } // 先過濾再遍歷四、注意事項
避免副作用forEach 應僅用于遍歷,不要在其中修改外部變量(除非必要)。
// ? 不推薦:修改外部狀態(tài)
var count = 0
list.forEach { count++ }
// ? 推薦:使用 `count()` 函數(shù)
val count = list.size不要修改集合本身
遍歷時修改集合(如增刪元素)可能導致 ConcurrentModificationException。
性能考量
對大數(shù)據(jù)量或性能敏感場景,優(yōu)先使用 for 循環(huán)(性能略優(yōu))。
五、常見場景示例
1?? 遍歷并處理元素
val numbers = listOf(10, 20, 30)
numbers.forEach {
val squared = it * it
println(squared)
}2?? 遍歷文件內(nèi)容
File("data.txt").readLines().forEach { line ->
println(line.trim())
}3?? 驗證數(shù)據(jù)
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} 未成年!" }
}六、總結(jié)
• 核心作用:遍歷集合元素并執(zhí)行操作。
• 適用場景:簡單遍歷、無需返回值的操作。
• 替代方案:需要復雜控制流時用 for 循環(huán);需要返回新集合時用 map/filter。
通過 forEach 可以讓代碼更簡潔,但需注意其局限性。
到此這篇關(guān)于kotlin的函數(shù)forEach的文章就介紹到這了,更多相關(guān)kotlin函數(shù)forEach內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android中自定義View實現(xiàn)圓環(huán)等待及相關(guān)的音量調(diào)節(jié)效果
這篇文章主要介紹了Android中自定義View實現(xiàn)圓環(huán)等待及相關(guān)的音量調(diào)節(jié)效果,邏輯非常簡單,或許繪圖方面更加繁瑣XD 需要的朋友可以參考下2016-04-04

