Kotlin Set filterNot()
Syntax & Examples


Set.filterNot() extension function

The filterNot() extension function in Kotlin filters elements in a set, returning a list of elements that do not match the given predicate.


Syntax of Set.filterNot()

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

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

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

Parameters

ParameterOptional/RequiredDescription
predicaterequiredA function that takes an element and returns true if the element should be excluded from the result.

Return Type

Set.filterNot() returns value of type List.



✐ Examples

1 Filtering out even numbers

Using filterNot() to filter elements in a set, excluding even numbers.

For example,

  1. Create a set of integers.
  2. Define a predicate function that returns true for even numbers.
  3. Use filterNot() to exclude even numbers from the set.
  4. Print the resulting list.

Kotlin Program

fun main(args: Array<String>) {
    val numbers = setOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    val oddNumbers = numbers.filterNot { it % 2 == 0 }
    println(oddNumbers)
}

Output

[1, 3, 5, 7, 9]

2 Filtering out null values

Using filterNot() to filter elements in a set, excluding null values.

For example,

  1. Create a set containing integers and null values.
  2. Define a predicate function that returns true for null values.
  3. Use filterNot() to exclude null values from the set.
  4. Print the resulting list.

Kotlin Program

fun main(args: Array<String>) {
    val mixedSet: Set<Int?> = setOf(1, 2, null, 4, null, 6)
    val nonNulls = mixedSet.filterNot { it == null }
    println(nonNulls)
}

Output

[1, 2, 4, 6]

3 Filtering out strings of length less than 3

Using filterNot() to filter elements in a set, excluding strings with a length less than 3.

For example,

  1. Create a set of strings.
  2. Define a predicate function that returns true for strings with a length less than 3.
  3. Use filterNot() to exclude these strings from the set.
  4. Print the resulting list.

Kotlin Program

fun main(args: Array<String>) {
    val strings = setOf("a", "ab", "abc", "abcd")
    val longStrings = strings.filterNot { it.length < 3 }
    println(longStrings)
}

Output

["abc", "abcd"]

Summary

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