Kotlin List mapNotNullTo()
Syntax & Examples


Syntax of List.mapNotNullTo()

The syntax of List.mapNotNullTo() extension function is:

fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapNotNullTo( destination: C, transform: (T) -> R? ): C

This mapNotNullTo() extension function of List applies the given transform function to each element in the original collection and appends only the non-null results to the given destination.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 1, 2, 3, 4, 5.
  • We create a mutable destination list named destination.
  • We use the mapNotNullTo() function with a transform function that checks if the value is even.
  • We append only non-null results to the destination list.
  • The resulting destination list, result, is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5)
    val destination = mutableListOf<String>()
    val result = list.mapNotNullTo(destination) { value -> if (value % 2 == 0) "\$value is even" else null }
    println("Mapped list: \$result")
}

Output

Mapped list: [2 is even, 4 is even]

2 Example

In this example,

  • We create a list of characters named list containing elements 'a', 'b', 'c'.
  • We create a mutable destination list named destination.
  • We use the mapNotNullTo() function with a transform function that checks if the value is 'a'.
  • We append only non-null results to the destination list.
  • The resulting destination list, result, is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', 'c')
    val destination = mutableListOf<String>()
    val result = list.mapNotNullTo(destination) { value -> if (value == 'a') "\$value is found" else null }
    println("Mapped list: \$result")
}

Output

Mapped list: [a is found]

3 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry".
  • We create a mutable destination list named destination.
  • We use the mapNotNullTo() function with a transform function that checks if the value starts with 'b'.
  • We append only non-null results to the destination list.
  • The resulting destination list, result, is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry")
    val destination = mutableListOf<String>()
    val result = list.mapNotNullTo(destination) { value -> if (value.startsWith('b')) "\$value starts with 'b'" else null }
    println("Mapped list: \$result")
}

Output

Mapped list: [banana starts with 'b']

Summary

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