Kotlin List filterNotTo()
Syntax & Examples


Syntax of List.filterNotTo()

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

fun <T, C : MutableCollection<in T>> Iterable<T>.filterNotTo( destination: C, predicate: (T) -> Boolean ): C

This filterNotTo() extension function of List appends all elements not matching the given predicate to the given destination.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing integers.
  • We create an empty mutable list named result to store elements not matching the predicate.
  • We use the filterNotTo function on list1 with a predicate that filters out even numbers and appends the remaining numbers to 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 = mutableListOf<Int>()
    list1.filterNotTo(result) { it % 2 == 0 }
    println(result)
}

Output

[1, 3, 5]

2 Example

In this example,

  • We create a list named list2 containing strings.
  • We create an empty mutable list named result to store strings not starting with 'a'.
  • We use the filterNotTo function on list2 with a predicate that filters out strings starting with 'a' and appends the remaining strings to 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")
    val result = mutableListOf<String>()
    list2.filterNotTo(result) { it.startsWith('a') }
    println(result)
}

Output

[banana, cherry]

3 Example

In this example,

  • We create a list named list3 containing characters.
  • We create an empty mutable list named result to store characters not equal to 'a' or 'e'.
  • We use the filterNotTo function on list3 with a predicate that filters out 'a' and 'e' characters and appends the remaining characters to 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 = mutableListOf<Char>()
    list3.filterNotTo(result) { it == 'a' || it == 'e' }
    println(result)
}

Output

[b, c, d]

Summary

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