我想过滤一个列表并记录通过过滤器的项目,类似于此:
val evenNumbers = (1..10)
.filter { it % 2 == 0 }
.onFallThrough { println("dropped $it") } // wishful Kotlin
.toList()
然后,这将导致以下输出:
dropped 1
dropped 3
dropped 5
dropped 7
dropped 9
以及列表
evenNumbers
中收集的所有偶数。浏览Sequences的手册页时,我找不到任何可以执行此操作的东西。 Kotlin是否有办法实现这一目标?
最佳答案
我会使用 partition
:
val evenNumbers = (1..10)
.partition { it % 2 == 0 }
.let {
println("dropped ${it.second}")
it.first
}
它返回一个
Pair
,其first
属性包含与条件匹配的所有元素,其second
属性包含与条件不匹配的元素。
关于kotlin - 在Kotlin中使用Sequence时如何处理掉入过滤器的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55456415/