Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

filternot
mutablelist
kotlin
communitycreator

How to use the filterNot() method of MutableList in Kotlin

Programming Bytes

Overview

The filterNot() function in Kotlin gets all the elements of the MutableList that don’t match the provided predicateA predicate is a functional interface that takes one argument and returns either “true” or “false,” based on the condition defined. function. Therefore, this method returns a list of elements for which the predicate function returns False.

Syntax

inline fun <T> Iterable<T>.filterNot(
    predicate: (T) -> Boolean
): List<T>

Parameter

This method takes the predicate function as an argument.

Return Value

This method returns a List object that contains all elements that don’t match the given predicate function.

Code

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]

}
Using the filterNot() method to get elements that don't match the given predicate

Explanation

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.

RELATED TAGS

filternot
mutablelist
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring