Kotlin List - filterNot() Function



The Kotlin List filterNot() function filters the element of a list that does not match a given predicate. It returns a new list containing only those elements that do not satisfy the condition defined by the predicate.

Syntax

Following is the syntax of Kotlin list filterNot() function −

list.filterNot { predicate }

Parameters

This function accepts lambda function to define a logic to do not filter the list element.

Return value

This function returns a list containing only those elements that does not satisfy the predicate.

Example 1: Filter Odd Number

Let's see a basic example of the filterNot() function, which return a list that does not contains even number −

fun main(args: Array<String>) {
   val numbers = listOf(2, 3, 4, 6, 7, 10)
   println(numbers.filterNot{ it % 2 == 0})
}

Output

Following is the output −

[3, 7]

Example 2: Filter String by Length

In the following example, we use the filterNot() to filter the string from the list which do not have a length less than 5 −

fun main(args: Array<String>){
   val words = listOf("Kotlin", "Java", "C++", "Python")
   val shortWords = words.filterNot { it.length <= 4 }
   println(shortWords)
}

Output

Following is the output −

[Kotlin, Python]

Example 3: Filter Elements that Dissatisfy Predicate

This is another example of the filterNot() function. Here, we create a custom function to filter number which is not greater than 0 −

// create a custom function
fun isPositive(number: Int): Boolean = number > 0
fun main(args: Array<String>){
   val numbers = listOf(-3, 0, 2, 5, -1)
   val positiveNumbers = numbers.filterNot(::isPositive)
   println(positiveNumbers)
}

Output

Following is the output −

[-3, 0, -1]
kotlin_lists.htm
Advertisements