不同的是当你使用
Sequence
它只会在迭代元素时运行函数。例如:
val numbers = 1 .. 50
val output = numbers.asSequence().filter{
println("Filtering $it")
it < 10
}.map{
println("Mapping $it")
Pair("Kotlin", it)
}
不会打印任何内容,因为您没有重复
output
检查文档有助于:
/**
* Creates a [Sequence] instance that wraps the original collection
* returning its elements when being iterated.
*/
public fun <T> Iterable<T>.asSequence(): Sequence<T> {
return Sequence { this.iterator() }
}
使用
顺序
map
在
Collection
结果将转换为
List
带着一个
顺序
就像
Stream