The filterNot() extension function in Kotlin filters elements in a set, returning a list of elements that do not match the given predicate.
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.
Parameter | Optional/Required | Description |
---|---|---|
predicate | required | A function that takes an element and returns true if the element should be excluded from the result. |
Set.filterNot() returns value of type List
.
Using filterNot() to filter elements in a set, excluding even numbers.
For example,
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)
}
[1, 3, 5, 7, 9]
Using filterNot() to filter elements in a set, excluding null values.
For example,
fun main(args: Array<String>) {
val mixedSet: Set<Int?> = setOf(1, 2, null, 4, null, 6)
val nonNulls = mixedSet.filterNot { it == null }
println(nonNulls)
}
[1, 2, 4, 6]
Using filterNot() to filter elements in a set, excluding strings with a length less than 3.
For example,
fun main(args: Array<String>) {
val strings = setOf("a", "ab", "abc", "abcd")
val longStrings = strings.filterNot { it.length < 3 }
println(longStrings)
}
["abc", "abcd"]
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.