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