Z
ZHANK
集合与泛型

集合操作

map/filter/reduce/flatMap/fold/groupBy/take/drop 常用操作

集合操作

Kotlin 标准库提供丰富的集合操作——map/filter/reduce/groupBy 等。

学完本章你将: 掌握 map/filter/reduce/flatMap/fold/groupBy/take/drop。


变换与过滤

kotlin
val nums = listOf(1, 2, 3, 4, 5)

nums.map { it * 2 }             // [2, 4, 6, 8, 10]
nums.filter { it % 2 == 0 }     // [2, 4]
nums.filterNot { it % 2 == 0 }  // [1, 3, 5]

归约

kotlin
nums.reduce { acc, n -> acc + n }      // 15(求和)
nums.fold(0) { acc, n -> acc + n }     // 15(带初始值)
nums.fold("") { acc, n -> "$acc$n" }   // "12345"

分组与排序

kotlin
val words = listOf("apple", "banana", "apricot", "blueberry")

words.groupBy { it.first() }         // {a=[apple, apricot], b=[banana, blueberry]}
words.sortedBy { it.length }         // 按长度排序
words.sortedDescending()             // 降序

截取

kotlin
val nums = listOf(1, 2, 3, 4, 5, 6)

nums.take(3)          // [1, 2, 3]
nums.takeLast(2)      // [5, 6]
nums.drop(3)          // [4, 5, 6]
nums.dropLast(2)      // [1, 2, 3, 4]

nums.takeWhile { it < 4 }     // [1, 2, 3]

其他常用

kotlin
nums.any { it > 3 }         // true——存在
nums.all { it > 0 }         // true——全部
nums.none { it < 0 }        // true——不存在
nums.count { it % 2 == 0 }  // 2——计数
nums.distinct()             // 去重
nums.chunked(2)             // [[1,2], [3,4], [5,6]]