kotlin: 比较list和sequence的区别

一,sequence的运行:

代码:

        //处理按钮点击事件
        binding.button1.setOnClickListener {
                val list = listOf(1, 2, 3, 4, 5)
                val seq1 = list.asSequence()
                seq1.filter {
                    println("filter1 $it")
                    it % 2 == 0
                }
                .map {
                    println("map1 $it")
                    it * 2
                }

                seq1.filter {
                    println("filter2 $it")
                    it % 2 == 0
                }
                .map {
                    println("map2 $it")
                    it * 2
                }.forEach(::println)
        }

运行结果:

image

二,list的运行:

代码:

        //处理按钮点击事件
        binding.button2.setOnClickListener {
            listOf(1, 2, 3, 4, 5)
                .filter {
                    println("filter $it")
                    it % 2 == 0
                }
                .map {
                    println("map $it")
                    it * 2
                }
        }

运行结果:

image

三,总结:

 Kotlin 的集合操作(如 mapfilter)默认是急切的,
 即每一步操作都会立即执行并生成中间结果


Sequence 的操作是惰性的,不会立即执行中间操作,
直到在调用终端操作(如 toListforEach)时才会执行整个操作链

普通集合:每次链式操作(如 filter -> map -> take)都会生成新的中间集合,导致内存占用与元素数量成线性增长;

Sequence:所有操作合并为一个“处理链”,逐个元素依次执行所有操作,无中间集合生成;

posted @ 2025-08-09 18:21  刘宏缔的架构森林  阅读(8)  评论(0)    收藏  举报