forEach
,这意味着仅查看20个整数? 码:
class Tests {
@Test
fun test() {
var counter = 0
(1..10_000_000).filter { it % 2 == 1 }.forEach {
counter++
if (counter > 10)
return
}
}
}
最佳答案
您的代码示例使用了对 Iterable<T>
的操作,该操作非常有效: .filter { ... }
调用将处理整个范围并产生一个存储中间结果的列表。
要改变这种情况,请考虑使用惰性工作的 Sequence<T>
(例如搭配 .asSequence()
),以便诸如 .filter { ... }
之类的中间操作会产生另一个惰性序列,并且仅在通过诸如 .forEach { ... }
之类的终端操作查询项目时才起作用:
(1..10000000).asSequence()
.filter { it % 2 == 1 }
.forEach { /* ... */ }
另请:Kotlin's Iterable and Sequence look exactly same. Why are two types required?
关于collections - Kotlin中的流处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48264574/