Filtering a list by a predicate and putting the results into a new list

Viewed 122

Im pretty new to programming,so I need to filter a list by a predicate and make a new list of the results without changing the list I filtered. My Problem is, that always all elements of the list to be filtered get put into the newList, and i dont know why.

Edit: I am not allowed to use build in - functions like filter.

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
1 Answers

Kotlin has a function for this, filter which will do what you want:

val list = listOf(1, 2, 3)

val result = list.filter { it > 2 }

println(result.joinToString()) // [3]

If you are not allowed to use filter you can just re-implement it:

fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
    val result = mutableListOf<T>()
    forEach { if(predicate(it)) result.add(it) }
    return result
}
Related