代码之家  ›  专栏  ›  技术社区  ›  dev_android

在Kotlin的数组中添加asSequence()的优点

  •  4
  • dev_android  · 技术社区  · 7 年前

    任何人都可以帮我指出以下代码中使用asSequence()的区别。

    val numbers = 1 .. 50
        val output = numbers.filter{ it < 10 }.map{ Pair("Kotlin", it)}
        output.forEach(::println)
    

    添加 asSequence()

    val numbers = 1 .. 50
    val output = numbers.asSequence().filter{ it < 10 }.map{ Pair("Kotlin", it)}
    output.forEach(::println)
    
    1 回复  |  直到 7 年前
        1
  •  10
  •   Adam Arold    7 年前

    不同的是当你使用 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

    推荐文章