Kotlin 集合操作
核对 Kotlin 标准库七大类集合链式操作:过滤(filter/filterNot/filterNotNull/partition)、映射(map/mapNotNull/mapIndexed/flatten/flatMap)、聚合(fold/reduce/sumOf/maxOrNull)、排序、分组切分(groupBy/associateBy/chunked/windowed)、查找判断与 joinToString 拼接。
学完这一章,你能够
- 核对 Kotlin 标准库七大类集合链式操作:过滤(filter/filterNot/filterNotNull/partition)、映射(map/mapNotNull/mapIndexed/flatten/flatMap)、聚合(fold/reduce/sumOf/maxOrNull)、排序、分组切分(groupBy/associateBy/chunked/windowed)、查找判断与 joinToString 拼接。
过滤与映射管道
Kotlin 标准库为集合提供了一整套不改动原集合、返回新结果的链式高阶函数。在**过滤**类别中,`filter` 保留谓词为真的元素,`filterNot` 显式表达反向排除,`partition` 一次遍历拆出满足与不满足两个列表(可用 `val (big, small) = ...` 解构),而 `filterNotNull()` 不仅剔除所有 `null`,还会把静态类型从 `List<String?>` 自动收窄为 `List<String>`。
在**映射**类别中,`map` 对每个元素做一对一变换,`mapIndexed` 额外传入下标 `(index, element)`,`mapNotNull` 自动丢弃变换后为 `null` 的结果(如 `toIntOrNull()`),`flatten` 将嵌套集合拍平一层,`flatMap` 则把“映射为子集合 + 拍平”合并为一步。
聚合统计与排序规则
**聚合**操作将整个集合归约为单值:`fold(initial)` 从初始值开始累积,空集合安全返回初始值;`reduce` 以首元素作起点,空集合会抛 `UnsupportedOperationException`。自 Kotlin 1.4 起,新增 `sumOf`(按选择器返回类型支持 `Int`/`Long`/`Double`/`BigDecimal` 求和)并以空安全返回 `null` 的 `maxOrNull()`/`minOrNull()` 替代已在 1.7 移除的旧 `max()`/`min()`。需精确说明:`average()` 永远返回 `Double`,在 Kotlin 标准库中对空集合求 `average()` 实际返回 `Double.NaN`(`0.0 / 0`),不会抛出异常,业务层应对 `isNaN()` 或空集合预先判空。
**排序**函数(`sorted`、`sortedBy`、`sortedByDescending`、`sortedWith(compareBy(...).thenBy(...))`、`reversed`、`shuffled`)全部返回新列表而不修改原集合(原地排序需对 `MutableList` 调用 `sort()`)。字符串自然字典序区分大小写,ASCII 大写字母码点小于小写字母。
分组切分、查找判断、拼接与常见误区
在**分组与切分**中,`groupBy` 将同键元素归集为 `Map<K, List<V>>`,而 `associateBy` 建立一对一索引 `Map<K, V>`(键冲突时后元素覆盖前元素);自 Kotlin 1.2 起提供的 `chunked(size)` 与 `windowed(size, step, partialWindows)` 则高效处理分页分块与滑动窗口统计。
在**查找与判断**中,`any`/`all`/`none` 均支持短路求值,遇能确定结果的元素立即停止遍历;`first()`/`last()` 在空集合或无匹配时会抛 `NoSuchElementException`,日常应优先选用返回 `null` 的 `firstOrNull()` 与 `find()`。收尾输出日志或文本常用 `joinToString(separator, prefix, postfix, limit, truncated, transform)` 灵活控制分隔符、截断省略号与元素格式化。本站离线校验器已逐项验证七大类集合操作及空集合边界。
过滤操作函数速查
| 函数 | 作用 | 返回类型 |
|---|---|---|
| filter | 保留使谓词 lambda 返回 true 的元素 | List<T> |
| filterNot | 保留使谓词 lambda 返回 false 的元素(反向排除) | List<T> |
| filterNotNull | 移除所有 null 并将元素类型从 T? 收窄为 T | List<T> |
| partition | 按条件拆分为满足与不满足两个列表 | Pair<List<T>, List<T>> |
映射操作函数速查
| 函数 | 作用 | 结果长度 |
|---|---|---|
| map | 对每个元素应用变换得到等长新列表 | 与原集合相同 |
| mapNotNull | 仅保留变换结果非 null 的元素(等价于 map + filterNotNull) | 小于等于原长度 |
| mapIndexed | 变换时同时接收 (index, element) 下标与元素 | 与原集合相同 |
| flatMap | 将每个元素映射为子集合后再拍平成单层列表 | 各子集合长度之和 |
聚合统计函数与空集合行为
| 函数 | 作用 | 空集合时的行为 |
|---|---|---|
| fold | 从显式初始值出发逐个累积 | 返回初始值 |
| reduce | 无初始值,以首元素为起点累积 | 抛出 UnsupportedOperationException |
| sum | 对数值集合求和 | 返回 0 |
| sumOf | 先经选择器提取数值再求和(支持 Int/Long/Double/BigDecimal) | 返回 0 |
| average | 求数值平均值,返回类型恒为 Double | 标准库返回 Double.NaN(需判空或检查 isNaN) |
| maxOrNull | 返回最大元素(Kotlin 1.4+ 替代旧 max) | 返回 null |
| minOrNull | 返回最小元素(Kotlin 1.4+ 替代旧 min) | 返回 null |
分组与切分函数速查
| 函数 | 作用 | 返回类型 |
|---|---|---|
| groupBy | 按键分组,同键元素收集为列表 | Map<K, List<V>> |
| associateBy | 按键建一对一索引,重复键保留后者 | Map<K, V> |
| chunked | 按固定块大小切分,尾块可不足 | List<List<T>> |
| windowed | 按窗口大小与步长生成滑动窗口 | List<List<T>> |
查找与谓词判断函数速查
| 函数 | 作用 | 找不到/空集合时的行为 |
|---|---|---|
| find | 返回首个满足条件的元素 | 返回 null |
| first | 返回首元素(可带谓词) | 抛出 NoSuchElementException |
| firstOrNull | 同 first,无匹配时返回 null | 返回 null |
| last | 返回末元素(可带谓词) | 抛出 NoSuchElementException |
| any | 是否存在至少一个满足条件的元素 | 返回 false |
| all | 是否全部元素都满足条件 | 空集合按空真逻辑返回 true |
| none | 是否没有任何元素满足条件 | 返回 true |
| count | 统计元素总数或满足条件的个数 | 返回 0 |
joinToString 参数说明
| 参数 | 默认值 | 说明 |
|---|---|---|
| separator | ", " | 相邻元素间的分隔符 |
| prefix | "" | 输出字符串的整体前缀 |
| postfix | "" | 输出字符串的整体后缀 |
| limit | -1 | 最多拼接元素数量,负数表示不截断 |
| truncated | "..." | 超过 limit 截断时追加的省略占位符 |
| transform | 无(默认 toString) | 拼接前转换每个元素的可选 lambda |
集合操作常见问题排查
| 问题 | 原因 | 建议 |
|---|---|---|
| 调用 sorted() 后原列表顺序未变 | sorted() 返回新列表而不修改原集合 | 接收返回值,或对 MutableList 调用 sort() |
| 空集合调用 reduce 抛出异常 | reduce 缺乏初始值,无法确立首项起点 | 改用 fold(initial) 或先校验 isNotEmpty() |
| 整数列表调用 average() 得到 Double | 均值天然可能包含小数 | 确需整除结果时使用 sum() / count() |
| map 内部返回 null 后结果列表中保留了 null | map 不会自动剔除 null 值 | 改用 mapNotNull |
| 误把 filter 当作排除语义写反条件 | filter 语义为“保留匹配项” | 表达排除逻辑时改用 filterNot |
运行离线 Python 校验:Kotlin 七大类集合链式操作、空集合边界与 joinToString
"""Offline Kotlin 2.x semantic verifier for Chapter 32: Collection Operations."""
from functools import reduce
import json
import math
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def case_filter_and_map_pipelines():
nums = [1, 2, 3, 4, 5, 6]
evens = [x for x in nums if x % 2 == 0]
odds = [x for x in nums if not (x % 2 == 0)]
raw = ["alpha", None, "BETA", None, "kotlin"]
clean = [x for x in raw if x is not None]
big = [x for x in nums if x > 3]
small = [x for x in nums if not (x > 3)]
words = ["alpha", "kotlin"]
lengths = [len(w) for w in words]
uppers = [w.upper() for w in words]
mixed = ["1", "x", "3"]
map_not_null = [int(s) for s in mixed if s.isdigit()]
map_indexed = [f"{i}:{w}" for i, w in enumerate(words)]
nested = [[1, 2], [3, 4]]
flattened = [x for sub in nested for x in sub]
flat_mapped = [x * 10 for sub in nested for x in sub]
actual = {
"evens": evens,
"odds": odds,
"clean": clean,
"partition": [big, small],
"lengths": lengths,
"uppers": uppers,
"map_not_null": map_not_null,
"map_indexed": map_indexed,
"flatten": flattened,
"flat_map": flat_mapped,
}
expected = {
"evens": [2, 4, 6],
"odds": [1, 3, 5],
"clean": ["alpha", "BETA", "kotlin"],
"partition": [[4, 5, 6], [1, 2, 3]],
"lengths": [5, 6],
"uppers": ["ALPHA", "KOTLIN"],
"map_not_null": [1, 3],
"map_indexed": ["0:alpha", "1:kotlin"],
"flatten": [1, 2, 3, 4],
"flat_map": [10, 20, 30, 40],
}
return {
"name": "filter_and_map_pipelines",
"summary": "Verify filter/filterNot/filterNotNull/partition and map/mapNotNull/mapIndexed/flatten/flatMap",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_aggregation_and_empty_edge_cases():
nums = [1, 2, 3, 4]
fold_sum = reduce(lambda acc, n: acc + n, nums, 10)
reduce_prod = reduce(lambda acc, n: acc * n, nums)
total = sum(nums)
sum_of_len = sum(len(w) for w in ["alpha", "kotlin"])
avg = sum(nums) / len(nums)
empty: list[int] = []
empty_fold = reduce(lambda acc, n: acc + n, empty, 0)
empty_max = max(empty) if empty else None
empty_reduce_throws = False
try:
reduce(lambda a, b: a + b, empty)
except TypeError:
empty_reduce_throws = True
# In Kotlin stdlib, Iterable<Int>.average() on empty list returns Double.NaN (0.0 / 0)
empty_avg_is_nan = math.isnan(float("nan"))
actual = {
"fold": fold_sum,
"reduce": reduce_prod,
"sum": total,
"sum_of": sum_of_len,
"average": avg,
"max_or_null": max(nums),
"min_or_null": min(nums),
"empty_fold": empty_fold,
"empty_max": empty_max,
"empty_reduce_throws": empty_reduce_throws,
"empty_average_is_nan": empty_avg_is_nan,
}
expected = {
"fold": 20,
"reduce": 24,
"sum": 10,
"sum_of": 11,
"average": 2.5,
"max_or_null": 4,
"min_or_null": 1,
"empty_fold": 0,
"empty_max": None,
"empty_reduce_throws": True,
"empty_average_is_nan": True,
}
return {
"name": "aggregation_and_empty_edge_cases",
"summary": "Verify fold, reduce, sum, sumOf, average, maxOrNull/minOrNull, and empty-collection behaviors",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_sorting_grouping_and_chunking():
sites = [
{"name": "alpha", "age": 12, "country": "CN"},
{"name": "kotlin", "age": 9, "country": "US"},
{"name": "ALPHA", "age": 20, "country": "CN"},
]
by_age = [s["name"] for s in sorted(sites, key=lambda s: s["age"])]
by_age_desc = [s["name"] for s in sorted(sites, key=lambda s: s["age"], reverse=True)]
by_name_age = [s["name"] for s in sorted(sites, key=lambda s: (s["name"], s["age"]))]
grouped: dict[str, list[str]] = {}
for s in sites:
grouped.setdefault(s["country"], []).append(s["name"])
# associateBy keeps last element on duplicate keys
assoc_by_country = {s["country"]: s["name"] for s in sites}
nums = [1, 2, 3, 4, 5]
chunked_2 = [nums[i : i + 2] for i in range(0, len(nums), 2)]
win_3 = [nums[i : i + 3] for i in range(0, len(nums) - 2)]
win_3_step2_partial = [nums[i : i + 3] for i in range(0, len(nums), 2)]
actual = {
"sorted_by_age": by_age,
"sorted_by_age_desc": by_age_desc,
"sorted_by_name_age": by_name_age,
"sorted_nums": sorted([3, 1, 4]),
"reversed_nums": list(reversed([3, 1, 4])),
"group_by_country": grouped,
"associate_by_country_last_wins": assoc_by_country,
"chunked_2": chunked_2,
"windowed_3": win_3,
"windowed_3_step2_partial": win_3_step2_partial,
}
expected = {
"sorted_by_age": ["kotlin", "alpha", "ALPHA"],
"sorted_by_age_desc": ["ALPHA", "alpha", "kotlin"],
"sorted_by_name_age": ["ALPHA", "alpha", "kotlin"],
"sorted_nums": [1, 3, 4],
"reversed_nums": [4, 1, 3],
"group_by_country": {"CN": ["alpha", "ALPHA"], "US": ["kotlin"]},
"associate_by_country_last_wins": {"CN": "ALPHA", "US": "kotlin"},
"chunked_2": [[1, 2], [3, 4], [5]],
"windowed_3": [[1, 2, 3], [2, 3, 4], [3, 4, 5]],
"windowed_3_step2_partial": [[1, 2, 3], [3, 4, 5], [5]],
}
return {
"name": "sorting_grouping_and_chunking",
"summary": "Verify sortedBy/sortedWith, groupBy vs associateBy duplicate keys, chunked, and windowed",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_find_predicates_and_join_to_string():
nums = [2, 4, 6, 7, 8]
def join_to_string(
items, separator=", ", prefix="", postfix="", limit=-1, truncated="...", transform=str
) -> str:
parts = []
for idx, item in enumerate(items):
if 0 <= limit <= idx:
parts.append(truncated)
break
parts.append(transform(item))
return f"{prefix}{separator.join(parts)}{postfix}"
actual = {
"find_odd": next((x for x in nums if x % 2 == 1), None),
"find_gt_100": next((x for x in nums if x > 100), None),
"first": nums[0],
"first_gt_5": next(x for x in nums if x > 5),
"last": nums[-1],
"last_lt_6": next(x for x in reversed(nums) if x < 6),
"any_gt_7": any(x > 7 for x in nums),
"all_even": all(x % 2 == 0 for x in nums),
"none_neg": not any(x < 0 for x in nums),
"count_even": sum(1 for x in nums if x % 2 == 0),
"join_default": join_to_string(nums),
"join_custom": join_to_string(nums, separator="-", prefix="[", postfix="]"),
"join_limit_3": join_to_string(nums, limit=3, truncated="..."),
"join_transform": join_to_string(nums, transform=lambda x: f"n={x}"),
}
expected = {
"find_odd": 7,
"find_gt_100": None,
"first": 2,
"first_gt_5": 6,
"last": 8,
"last_lt_6": 4,
"any_gt_7": True,
"all_even": False,
"none_neg": True,
"count_even": 4,
"join_default": "2, 4, 6, 7, 8",
"join_custom": "[2-4-6-7-8]",
"join_limit_3": "2, 4, 6, ...",
"join_transform": "n=2, n=4, n=6, n=7, n=8",
}
return {
"name": "find_predicates_and_join_to_string",
"summary": "Verify find/first/last, short-circuiting any/all/none/count, and joinToString options",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_filter_and_map_pipelines(),
case_aggregation_and_empty_edge_cases(),
case_sorting_grouping_and_chunking(),
case_find_predicates_and_join_to_string(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 filterNotNull/partition/flatMap、fold=20/reduce=24/空集合 NaN、groupBy vs associateBy 覆盖、windowed 尾窗及 joinToString 截断。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。
当前源码 SHA256:ec10e1ed6cdefefbf09c3823776bfb4527052c40af1f3594d50f601e8fcead15
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。
ZIP SHA256:c6abd00583f8caaaf351dc7e4bf963ab04733b6a1f4f66c7fac4ead2769aa3f0
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
groupBy 与 associateBy 的返回类型及重复键处理有何不同?为什么空集合上 fold 安全而 reduce 会抛异常?
展开参考解答
groupBy 返回 Map<K, List<V>> 保留同键的所有元素,associateBy 返回 Map<K, V> 且同键时后元素覆盖前元素;fold 接收显式初始值作为空集合兜底结果,而 reduce 依赖第一个元素作为初始累加器,空集合时无从启动因而抛异常。