The filterNot()
function in Kotlin gets all the elements of the MutableList
that don’t match the provided False
.
inline fun <T> Iterable<T>.filterNot(
predicate: (T) -> Boolean
): List<T>
This method takes the predicate function as an argument.
This method returns a List
object that contains all elements that don’t match the given predicate function.
The code below demonstrates how to use the filterNot()
method in Kotlin:
fun main() {val list: List<Int> = mutableListOf(1, 2, 3, 4, 5)println("The list is : $list")val greaterThan3 = list.filterNot{ it > 3 }println("Elements which are not greater than3 $greaterThan3") // [1, 2, 3]val greaterThan0 = list.filterNot { it > 0 }println("Elements which are not greater than 0 : $greaterThan0") // [1, 2, 3]}
Line 3: We create a new MutableList
object named list
, using the mutableListOf()
method. For the mutableListOf()
method, we provide 1
,2
,3
,4
, and 5
as arguments. All the provided arguments are present in the returned list
.
Line 6: We use the filterNot()
method with a predicate function as an argument. This function returns False
if the element is not greater than 3
. The filterNot()
method returns a list with elements for which the predicate function returns False
. In this case, the predicate function returns False
for the elements 1
, 2
, and 3
. So, the filterNot()
method returns [1,2,3]
as the result.
Line 8: We use the filterNot()
method with a predicate function as an argument. This function returns False
if the element is not greater than 0
. In this case, all elements are greater than 0
. So, the filterNot()
method returns an empty list []
as the result.