Kotlin Set filterNotNull()
Syntax & Examples


Set.filterNotNull() extension function

The filterNotNull() extension function in Kotlin filters elements in a set, returning a list of elements that are not null.


Syntax of Set.filterNotNull()

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

fun <T : Any> Set<T?>.filterNotNull(): List<T>

This filterNotNull() extension function of Set returns a list containing all elements that are not null.

Return Type

Set.filterNotNull() returns value of type List.



✐ Examples

1 Filtering out null values from a set of integers

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

For example,

  1. Create a set containing integers and null values.
  2. Use filterNotNull() to exclude null values from the set.
  3. Print the resulting list.

Kotlin Program

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

Output

[1, 2, 4, 6]

2 Filtering out null values from a set of strings

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

For example,

  1. Create a set containing strings and null values.
  2. Use filterNotNull() to exclude null values from the set.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val mixedSet: Set<String?> = setOf("a", null, "b", "c", null)
    val nonNullStrings = mixedSet.filterNotNull()
    println(nonNullStrings)
}

Output

["a", "b", "c"]

3 Filtering out null values from a set of mixed types

Using filterNotNull() to filter elements in a set containing mixed types, excluding null values.

For example,

  1. Create a set containing elements of different types and null values.
  2. Use filterNotNull() to exclude null values from the set.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val mixedSet: Set<Any?> = setOf(1, "two", null, 3.0, null, "four")
    val nonNullElements = mixedSet.filterNotNull()
    println(nonNullElements)
}

Output

[1, "two", 3.0, "four"]

Summary

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