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

Kotlin 序列

核对 Kotlin Sequence<T> 惰性求值管道、与立即求值 Iterable 的中间列表分配及步数对比、四种序列创建方式(sequenceOf/asSequence/generateSequence/sequence{yield})、constrainOnce 约束、中间与末端操作区分以及选型准则。

学完这一章,你能够

  • 核对 Kotlin Sequence<T> 惰性求值管道、与立即求值 Iterable 的中间列表分配及步数对比、四种序列创建方式(sequenceOf/asSequence/generateSequence/sequence{yield})、constrainOnce 约束、中间与末端操作区分以及选型准则。

序列本质与立即/惰性求值步数对比

序列(`Sequence<T>`)不是存储数据的新容器,而是包裹在数据源外层的**惰性求值处理管道**:它仅保存“如何逐个产出并变换下一个元素”的规则,在末端操作触发前不做任何实际计算。

与普通集合(`Iterable`)每调用一次 `filter` 或 `map` 就完整遍历一次并分配全新中间列表的“水平立即求值”不同,序列采用**元素逐个穿过整条操作链的垂直惰性求值**。在 `(1..10).filter { it % 2 == 0 }.map { it * it }.first { it > 20 }` 对比实验中,两者均得出 `36`,但集合执行了 `15` 次 lambda 且分配 2 个中间列表,而序列在找到 `6 * 6 = 36` 后立即短路终止,仅执行了 `9` 次 lambda 且零中间列表分配!本站离线验证器已精确复现 15 次 vs 9 次(及 50 万规模下 666,666 步 vs 668 步)的对比证明。

四种创建方式与中间/末端操作区分

创建序列主要有四种方式:`sequenceOf(...)` 直接包装已知元素;`collection.asSequence()` 将现有集合/数组转为序列;`generateSequence(seed) { next }` 基于种子与递推规则构造有限或无限序列(需搭配 `take`/`takeWhile` 截断);自 Kotlin 1.3 起提供的 `sequence { yield(...) }` 构建器允许在受限挂起块(`SequenceScope`)内用 `yield`/`yieldAll` 编写有状态生成器(如斐波那契数列),注意块内不能随意调用外部普通 `suspend` 函数。由 `Iterator.asSequence()` 包装的序列只能遍历一次,需显式约束单次消费时可调用 `constrainOnce()`(Kotlin 1.3 起)。

序列 API 严格分为**中间操作**(返回新 `Sequence`,如 `filter`、`map`、`take`、`onEach`,调用时不执行任何计算)与**末端操作**(触发管道执行并返回具体值或集合,如 `toList`、`first`、`count`、`forEach`)。跟踪 `sequenceOf(1..6).filter(...).map(...).toList()` 可清晰看到 `filter 1 -> filter 2 -> map 2 -> filter 3 -> filter 4 -> map 4...` 的逐元素交替输出。特别注意:`sorted`、`sortedBy` 等有状态操作必须先缓冲全部元素,严禁直接施加在未截断的无限序列上。

大规模提前终止收益、适用场景与常见误区

当数据规模达数十万/数百万且链尾存在 `first`/`find`/`take`/`any` 等提前终止操作时,序列能省去巨型中间集合分配与绝大部分冗余迭代,带来数量级的性能优势;但序列并非万能银弹——对于仅数十个元素的小集合或需多次遍历、随机下标访问的场景,序列引入的额外迭代器与 lambda 封装开销反而可能慢于直接集合操作。实用决策口诀:**小集合且末端为 `toList()` 继续用集合;大集合多步链式变换、无限流或带短路末端操作果断改用序列**。

集合(Iterable)与序列(Sequence)核心差异

对比项集合(Iterable)序列(Sequence)
求值时机立即求值,每步调用即刻执行惰性求值,仅在末端操作触发时计算
中间结果每一步都分配并填充新中间集合不生成中间集合,元素逐个流过管道
遍历次数每个操作各自完整遍历一次多步无状态操作融合为单次遍历
能否无限长不能,元素须全部驻留内存支持无限序列,配合 take/takeWhile 截断
小数据量性能更快,无额外状态机与包装层开销略慢,多出迭代器与函数对象调度开销
适用场景小集合、多次遍历或需随机下标访问大数据集多步变换、无限流或短路提前终止

序列四种创建方式速查

方式用途示例
sequenceOf由已知离散元素直接构造序列sequenceOf("alpha", "kotlin")
asSequence将既有集合、数组或迭代器转为序列listOf(1, 2).asSequence()
generateSequence基于初始种子与递推函数生成(可无限)generateSequence(1) { it * 2 }
sequence { }借助 SequenceScope 的 yield/yieldAll 按需产出sequence { yield(1) }

序列中间操作与末端操作分类

类别常见函数返回值
中间操作filter、map、mapNotNull、flatMap、take、drop、distinct、sorted、onEach新的 Sequence<R>
末端操作toList、toSet、first、find、count、sum、any、all、forEach、joinToString具体标量结果或集合

集合与序列工程选型指南

场景推荐原因
元素数量较少(几十个以内)集合中间列表开销极小,直接循环更快
数据量大且多步链式变换序列消除多个大型中间列表的堆分配与 GC 压力
链尾含 first/find/take/any 等短路操作序列命中目标即刻停止,跳过剩余全部元素
无限或长度未知的数据流序列集合无法在内存中容纳无限元素
同一结果需反复遍历多次集合序列每次触发末端操作都会重头计算
需要随机下标访问集合序列仅支持单向顺序迭代,无 O(1) 索引

序列常见问题排查

问题原因解决办法
编写完序列链但未产生任何日志或结果仅拼装了中间操作,未调用末端操作触发执行补上 toList、forEach、first 或 count 等末端操作
对同一序列第二次遍历抛 IllegalStateException由一次性 Iterator 包装或标记了 constrainOnce重新调用 asSequence(),或先物化为 List
在序列上调用 sorted 卡死或内存飙升排序属有状态操作,必须先读尽整个序列严禁直接用于无限序列,先用 take 限定上界
小集合改用序列后耗时反增序列多了多层迭代器包装与回调调度开销小数据量保持普通集合操作
在 sequence { } 内调用 delay 等普通挂起函数报错SequenceScope 标有 @RestrictsSuspension,仅允许 yield 系列异步挂起数据流请改用协程 Flow

运行离线 Python 校验:Kotlin 集合 15 步 vs 序列 9 步对比、无限生成器与逐元素轨迹

含完整源码 · 236 行
展开查看收起
python
"""Offline Kotlin 2.x semantic verifier for Chapter 33: Sequences."""
from itertools import islice, takewhile
import json

VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"


def case_eager_list_vs_lazy_sequence_steps():
    data = list(range(1, 11))

    # Eager Iterable: filter allocates intermediate list (10 checks), map allocates intermediate list (5 checks)
    list_steps = 0
    intermediate_lists = 0

    def eager_filter(xs):
        nonlocal list_steps, intermediate_lists
        out = []
        for x in xs:
            list_steps += 1
            if x % 2 == 0:
                out.append(x)
        intermediate_lists += 1
        return out

    def eager_map(xs):
        nonlocal list_steps, intermediate_lists
        out = []
        for x in xs:
            list_steps += 1
            out.append(x * x)
        intermediate_lists += 1
        return out

    list_res = next(x for x in eager_map(eager_filter(data)) if x > 20)

    # Lazy Sequence: element flows vertically through filter -> map -> first without intermediate lists
    seq_steps = 0

    def seq_filter(it):
        nonlocal seq_steps
        for x in it:
            seq_steps += 1
            if x % 2 == 0:
                yield x

    def seq_map(it):
        nonlocal seq_steps
        for x in it:
            seq_steps += 1
            yield x * x

    seq_res = next(x for x in seq_map(seq_filter(iter(data))) if x > 20)

    actual = {
        "list_result": list_res,
        "list_steps": list_steps,
        "list_intermediate_allocs": intermediate_lists,
        "seq_result": seq_res,
        "seq_steps": seq_steps,
        "seq_intermediate_allocs": 0,
    }
    expected = {
        "list_result": 36,
        "list_steps": 15,
        "list_intermediate_allocs": 2,
        "seq_result": 36,
        "seq_steps": 9,
        "seq_intermediate_allocs": 0,
    }
    return {
        "name": "eager_list_vs_lazy_sequence_steps",
        "summary": "Prove eager List executes 15 lambdas + 2 intermediate lists vs lazy Sequence 9 lambdas + 0 lists",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_sequence_builders_and_constrain_once():
    def generate_sequence(seed, nxt):
        cur = seed
        while cur is not None:
            yield cur
            cur = nxt(cur)

    def fib_sequence():
        a, b = 0, 1
        while True:
            yield a
            a, b = b, a + b

    class ConstrainedOnceSequence:
        def __init__(self, items):
            self._items = items
            self._consumed = False

        def iterate(self):
            if self._consumed:
                raise RuntimeError("IllegalStateException: This sequence can be consumed only once.")
            self._consumed = True
            return list(self._items)

    once = ConstrainedOnceSequence(["a", "b"])
    first_pass = once.iterate()
    second_failed = False
    try:
        once.iterate()
    except RuntimeError:
        second_failed = True

    actual = {
        "sequence_of": ["alpha", "beta", "kotlin"],
        "powers_take_5": list(islice(generate_sequence(1, lambda x: x * 2), 5)),
        "powers_take_while_100": list(takewhile(lambda x: x <= 100, generate_sequence(1, lambda x: x * 2))),
        "fib_take_8": list(islice(fib_sequence(), 8)),
        "constrain_once_first": first_pass,
        "constrain_once_second_throws": second_failed,
    }
    expected = {
        "sequence_of": ["alpha", "beta", "kotlin"],
        "powers_take_5": [1, 2, 4, 8, 16],
        "powers_take_while_100": [1, 2, 4, 8, 16, 32, 64],
        "fib_take_8": [0, 1, 1, 2, 3, 5, 8, 13],
        "constrain_once_first": ["a", "b"],
        "constrain_once_second_throws": True,
    }
    return {
        "name": "sequence_builders_and_constrain_once",
        "summary": "Verify sequenceOf, infinite generateSequence, yield Fibonacci sequence{}, and constrainOnce()",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_element_by_element_execution_trace():
    trace = []

    def lazy_filter(it):
        for x in it:
            trace.append(f"filter {x}")
            if x % 2 == 0:
                yield x

    def lazy_map(it):
        for x in it:
            trace.append(f"map {x}")
            yield x * 10

    pipeline = lazy_map(lazy_filter(iter([1, 2, 3, 4, 5, 6])))
    trace_before_terminal = list(trace)
    result = list(pipeline)

    actual = {
        "trace_before_terminal": trace_before_terminal,
        "trace_after_toList": trace,
        "result": result,
    }
    expected = {
        "trace_before_terminal": [],
        "trace_after_toList": [
            "filter 1",
            "filter 2",
            "map 2",
            "filter 3",
            "filter 4",
            "map 4",
            "filter 5",
            "filter 6",
            "map 6",
        ],
        "result": [20, 40, 60],
    }
    return {
        "name": "element_by_element_execution_trace",
        "summary": "Verify zero work before terminal op and vertical element-by-element execution order",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_large_range_short_circuit_savings():
    # Deterministic operation-count comparison for 1..500_000 (% 3 == 0, * 2, first > 1000)
    n = 500_000
    eager_filter_ops = n
    eager_map_ops = n // 3
    eager_total_ops = eager_filter_ops + eager_map_ops

    seq_filter_ops = 0
    seq_map_ops = 0
    seq_answer = None
    for x in range(1, n + 1):
        seq_filter_ops += 1
        if x % 3 == 0:
            seq_map_ops += 1
            doubled = x * 2
            if doubled > 1000:
                seq_answer = doubled
                break
    seq_total_ops = seq_filter_ops + seq_map_ops

    actual = {
        "answer": seq_answer,
        "eager_total_ops": eager_total_ops,
        "seq_total_ops": seq_total_ops,
        "seq_saves_over_99_percent": seq_total_ops * 100 < eager_total_ops,
    }
    expected = {
        "answer": 1002,
        "eager_total_ops": 666666,
        "seq_total_ops": 668,
        "seq_saves_over_99_percent": True,
    }
    return {
        "name": "large_range_short_circuit_savings",
        "summary": "Verify deterministic operation savings (668 vs 666666) for Sequence short-circuiting on 500k items",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_eager_list_vs_lazy_sequence_steps(),
        case_sequence_builders_and_constrain_once(),
        case_element_by_element_execution_trace(),
        case_large_range_short_circuit_savings(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
证明 (1..10) 链式求 36 集合需 15 步+2 中间列表而序列仅 9 步+0 列表;验证斐波那契前 8 项、constrainOnce 异常及 50 万规模 668 vs 666666 步。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

集合的 filter 会先遍历全部 10 个元素再由 map 处理全部 5 个偶数(共 15 次);序列逐个元素穿过 filter 与 map,处理到 6 时即产出 36 并立即短路(6 次 filter + 3 次 map = 9 次)。sorted() 需要读取所有元素才能排序,对无限序列会无限等待直至耗尽内存。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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