Kotlin Array - filterNot() Function



The Kotlin array filterNot() function is used to create a new list which not matching with the given condition or predicate. Takes a predicate as an argument and returns a list that doest not satisfy specified conditions.

The returned list preserves the entry iteration order of the original array.

Syntax

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

fun <T> Array<out T>.filterNot(predicate: (T) -> Boolean): List<T>

Parameters

This function accepts a predicate as a parameter. Predicate represent a condition which gives boolean value.

Return value

This function returns a list containing all elements that's not filtered according to the predicate or condition.

Example 1

Following is the basic example to demonstrate the use of filterNot() function −

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
   val list = number.filterNot{it>3}
   println("Not filtered list: $list")
}

Output

On execution of the above code we get the following result −

Not filtered list: [1, 2, 3]

Example 2

Now, let's see another example. Here, we use the filterNot() function to return a list containing element which are not filtered −

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
   val list = number.filterNot{it%2==0}
   println("Odd number: $list")
}

Output

After execution of the above code we get the following output −

Even number: [1, 3, 5, 7]

Example 3

The example below creates an array that stores strings. We then use the filterNot() function to display the elements whose length is less than 4 −

fun main(args: Array<String>) {
   val strings: Array<String> = arrayOf("hii", "Hello", "tutorix", "tutorialspoint")
   val filterNot = strings.filterNot{it.length>4}
   println("list: $filterNot")
}

Output

The above code produce following output −

list: [hii]
kotlin_arrays.htm
Advertisements