我对编程很陌生,所以我需要按谓词过滤列表并创建一个新的结果列表,而不更改我过滤的列表。我的问题是,要过滤的列表的所有元素总是被放入 newList 中,我不知道为什么。
编辑:我不允许使用内置 - 过滤器等功能。
fun filter(predicate: (Order) -> Boolean): OrderProcessing {
var currentNode = first
var newList: OrderProcessing = OrderProcessing()
while (currentNode != null) {
var next = currentNode.next
if (predicate(currentNode.order)) {
if (newList.first != null) {
var newerNode = newList.first
while (newerNode != null) {
newerNode = newerNode.next
}
currentNode.next = null
newerNode?.next = currentNode
println(currentNode.next)
}
else newList.first = currentNode
}
currentNode = next
}
println(newList)
return newList
Kotlin 有一个函数,filter
它会做你想做的事:
val list = listOf(1, 2, 3)
val result = list.filter { it > 2 }
println(result.joinToString()) // [3]
如果您不被允许使用filter
您可以重新实现它:
fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
val result = mutableListOf<T>()
forEach { if(predicate(it)) result.add(it) }
return result
}