蓝色天空.知识 · 实践 · 创造
我的收藏
Kotlin 教程目录 43章
Kotlin / LEARN BY DOING

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? 收窄为 TList<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 后结果列表中保留了 nullmap 不会自动剔除 null 值改用 mapNotNull
误把 filter 当作排除语义写反条件filter 语义为“保留匹配项”表达排除逻辑时改用 filterNot

运行离线 Python 校验:Kotlin 七大类集合链式操作、空集合边界与 joinToString

含完整源码 · 237 行
展开查看收起
python
"""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 截断。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2136.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Kotlin

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2136.zip

下载课程关联工程包:Kotlin

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

groupBy 返回 Map<K, List<V>> 保留同键的所有元素,associateBy 返回 Map<K, V> 且同键时后元素覆盖前元素;fold 接收显式初始值作为空集合兜底结果,而 reduce 依赖第一个元素作为初始累加器,空集合时无从启动因而抛异常。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习