Kotlin List mapIndexedNotNull()
Syntax & Examples


Syntax of List.mapIndexedNotNull()

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

fun <T, R : Any> Iterable<T>.mapIndexedNotNull( transform: (index: Int, T) -> R? ): List<R>

This mapIndexedNotNull() extension function of List returns a list containing only the non-null results of applying the given transform function to each element and its index in the original collection.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 1, 2, 3, 4, 5.
  • We use the mapIndexedNotNull() function with an index and value.
  • We apply a condition where if the index is even, we multiply the value by 2, otherwise we return null.
  • The resulting list, result, contains only non-null elements and is printed to standard output using println statement.

Kotlin Program

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

Output

Mapped list: [2, 6, 10]

2 Example

In this example,

  • We create a list of characters named list containing elements 'a', 'b', 'c'.
  • We use the mapIndexedNotNull() function with an index and value.
  • We apply a condition where if the index is 1, we convert the value to uppercase, otherwise we return null.
  • The resulting list, result, contains only non-null elements and is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', 'c')
    val result = list.mapIndexedNotNull { index, value -> if (index == 1) value.toUpperCase() else null }
    println("Mapped list: \$result")
}

Output

Mapped list: [B]

3 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry".
  • We use the mapIndexedNotNull() function with an index and value.
  • We apply a condition where if the length of the string is greater than 5, we return its length, otherwise we return null.
  • The resulting list, result, contains only non-null elements and is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry")
    val result = list.mapIndexedNotNull { index, value -> if (value.length > 5) value.length else null }
    println("Mapped list: \$result")
}

Output

Mapped list: [6, 6]

Summary

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