Kotlin Tutorials

Kotlin Set mapNotNull()
Syntax & Examples

Set.mapNotNull() extension function

The mapNotNull() extension function in Kotlin returns a list containing only the non-null results of applying the given transform function to each element in the original set.


Syntax of Set.mapNotNull()

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

fun <T, R : Any> Set<T>.mapNotNull(transform: (T) -> R?): List<R>

This mapNotNull() extension function of Set returns a list containing only the non-null results of applying the given transform function to each element in the original collection.

Parameters

ParameterOptional/RequiredDescription
transformrequiredA function that takes an element and returns the transformed result, which may be null.

Return Type

Set.mapNotNull() returns value of type List.



✐ Examples

1 Transforming a set of integers by doubling each element, filtering out nulls

Using mapNotNull() to transform a set of integers by doubling each element, and filtering out null results.

For example,

  1. Create a set of integers.
  2. Use mapNotNull() with a transform function that doubles each element and filters out nulls.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val doubled = numbers.mapNotNull { if (it % 2 == 0) it * 2 else null }
    println(doubled)
}

Output

[4, 8]

2 Transforming a set of strings by getting their lengths, filtering out nulls

Using mapNotNull() to transform a set of strings by getting the length of each string, and filtering out null results.

For example,

  1. Create a set of strings.
  2. Use mapNotNull() with a transform function that returns the length of each string, and filters out nulls.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val lengths = strings.mapNotNull { if (it.length > 3) it.length else null }
    println(lengths)
}

Output

[5]

3 Transforming a set of custom objects by extracting a specific property, filtering out nulls

Using mapNotNull() to transform a set of custom objects by extracting a specific property, and filtering out null results.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use mapNotNull() with a transform function that extracts a specific property from each object, and filters out nulls.
  4. Print the resulting list.

Kotlin Program

data class Person(val name: String, val age: Int)

fun main() {
    val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
    val names = people.mapNotNull { if (it.age > 30) it.name else null }
    println(names)
}

Output

[Charlie]

Summary

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