Kotlin Set filterNotNullTo()
Syntax & Examples


Set.filterNotNullTo() extension function

The filterNotNullTo() extension function in Kotlin filters elements in a set, appending all elements that are not null to the given destination collection.


Syntax of Set.filterNotNullTo()

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

fun <C : MutableCollection<in T>, T : Any> Set<T?>.filterNotNullTo(destination: C): C

This filterNotNullTo() extension function of Set appends all elements that are not null to the given destination.

Parameters

ParameterOptional/RequiredDescription
destinationrequiredThe collection to which the non-null elements will be appended.

Return Type

Set.filterNotNullTo() returns value of type C.



✐ Examples

1 Appending non-null integers to a list

Using filterNotNullTo() to filter elements in a set, appending non-null values to a list.

For example,

  1. Create a set containing integers and null values.
  2. Create an empty list to hold the non-null elements.
  3. Use filterNotNullTo() to append non-null values from the set to the list.
  4. Print the resulting list.

Kotlin Program

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

Output

[1, 2, 4, 6]

2 Appending non-null strings to a set

Using filterNotNullTo() to filter elements in a set, appending non-null values to another set.

For example,

  1. Create a set containing strings and null values.
  2. Create an empty set to hold the non-null elements.
  3. Use filterNotNullTo() to append non-null values from the set to the new set.
  4. Print the resulting set.

Kotlin Program

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

Output

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

3 Appending non-null elements of mixed types to a list

Using filterNotNullTo() to filter elements in a set containing mixed types, appending non-null values to a list.

For example,

  1. Create a set containing elements of different types and null values.
  2. Create an empty list to hold the non-null elements.
  3. Use filterNotNullTo() to append non-null values from the set to the list.
  4. Print the resulting list.

Kotlin Program

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

Output

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

Summary

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