Kotlin List filterNot()
Syntax & Examples


Syntax of List.filterNot()

The syntax of List.filterNot() extension function is:

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

This filterNot() extension function of List returns a list containing all elements not matching the given predicate.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing integers from 1 to 5.
  • We use the filterNot function on list1 to filter out elements that are even numbers.
  • The result, which is a list of odd numbers, is stored in result.
  • Finally, we print the value of result to standard output using the println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 2, 3, 4, 5)
    val result = list1.filterNot { it % 2 == 0 }
    println(result)
}

Output

[1, 3, 5]

2 Example

In this example,

  • We create a list named list2 containing strings.
  • We use the filterNot function on list2 to filter out elements that start with the letter 'a'.
  • The result, which is a list of strings excluding those starting with 'a', is stored in result.
  • Finally, we print the value of result to standard output using the println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf("apple", "banana", "cherry", "date")
    val result = list2.filterNot { it.startsWith("a") }
    println(result)
}

Output

[banana, cherry, date]

3 Example

In this example,

  • We create a list named list3 containing characters from 'a' to 'e'.
  • We use the filterNot function on list3 to filter out elements that are 'a' or 'e'.
  • The result, which is a list of characters excluding 'a' and 'e', is stored in result.
  • Finally, we print the value of result to standard output using the println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list3 = listOf('a', 'b', 'c', 'd', 'e')
    val result = list3.filterNot { it in listOf('a', 'e') }
    println(result)
}

Output

[b, c, d]

Summary

In this Kotlin tutorial, we learned about filterNot() extension function of List: the syntax and few working examples with output and detailed explanation for each example.