Z
ZHANK
集合与泛型

序列 Sequence

asSequence 惰性求值、中间/终端操作、与集合性能对比

序列 Sequence

Sequence 是惰性集合——操作只在需要时才执行,避免中间集合开销。

学完本章你将: 掌握 asSequence 惰性求值、中间/终端操作。


急需求值 vs 惰性求值

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

// 急切:每一步都创建新集合
nums
    .map { println("map $it"); it * 2 }     // 全部执行
    .filter { println("filter $it"); it > 5 }
// 输出: map 1-5, filter 2-10

// 惰性:一条条处理——不创建中间集合
nums.asSequence()
    .map { println("map $it"); it * 2 }
    .filter { println("filter $it"); it > 5 }
    .toList()                               // 终端操作——触发执行
// 输出: map1, filter2, map2, filter4, ...

中间 vs 终端操作

kotlin
// 中间操作(返回 Sequence)——不执行
.map { }  .filter { }  .take { }

// 终端操作(返回结果)——触发执行
.toList()  .toSet()  .first()  .count()  .forEach { }

何时用 Sequence

kotlin
// ✅ 数据量大、操作链长
bigList.asSequence()
    .map { expensive(it) }
    .filter { condition(it) }
    .take(10)           // 只处理前 10 个——提前终止
    .toList()

// ✅ 普通操作——直接用集合即可
smallList.map { it * 2 }.filter { it > 5 }