【发布时间】:2022-01-06 06:23:41
【问题描述】:
我正在尝试从列表中过滤掉某些项目,并以特定顺序将它们合并到最终列表中。第一个代码 sn-p 似乎效率低下,因为它创建了 2 个用于过滤的列表然后迭代它们但是该代码有效。第二个 sn-p 试图结合这两个过滤但是 map 运算符没有将项目添加到 otherNums 列表中
有人可以帮我理解为什么会这样吗?
片段 1:
fun main() {
val favItem = 0
val list = listOf(11, 12, 13, 2,3,4,5,6,7,10, favItem)
val greaterThan10 = list.filter{item -> item > 10}
val otherNums = list.asSequence().filter{item -> item != favItem}.filter{item -> item < 10}
println(" $greaterThan10") //the list is filled with proper numbers
println("merged list ${greaterThan10.plus(favItem).plus(otherNums)}")
}
结果:
[11, 12, 13]
merged list [11, 12, 13, 0, 2, 3, 4, 5, 6, 7]
片段 2:
fun main() {
val favItem = 0
val list = listOf(11, 12, 13, 2,3,4,5,6,7,10, favItem)
val greaterThan10 = mutableListOf<Int>()
val otherNums = list.asSequence().filter{item -> item != favItem}.map{
if(it > 10) {
greaterThan10.add(it)
}
it
}
.filter{item -> item != 10}
println("$greaterThan10") // the list is empty
println("merged list ${greaterThan10.plus(favItem).plus(otherNums)}")
}
结果:
[]
merged list [0, 11, 12, 13, 2, 3, 4, 5, 6, 7]
【问题讨论】:
-
您需要
greaterThan10列表还是只需要最后一个? -
不知道为什么,但删除
asSequence()使得greaterThan10至少被填满 -
@JoãoDias 我需要最后一个,但
greaterThan10列表通过检查greaterThan10中是否有正确的值来帮助调试 -
@IvoBeckers
asSequence有助于避免为每个filter创建 2 个单独的列表。效率更高一点 -
是的,我明白了。但由于某种原因,如果你把它排除在外,大于 10 确实会被填满。而且我不明白为什么,因为在这两种情况下,
greaterThan10.add(it)在打印之前都会被调用
标签: kotlin collections predicate