The mapIndexedNotNull() extension function in Kotlin returns a list containing only the non-null results of applying the given transform function to each element and its index in the original set.
The syntax of Set.mapIndexedNotNull() extension function is:
fun <T, R : Any> Set<T>.mapIndexedNotNull(transform: (index: Int, T) -> R?): List<R>
This mapIndexedNotNull() extension function of Set 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.
Parameter | Optional/Required | Description |
---|---|---|
transform | required | A function that takes an index and an element, and returns the transformed result, which may be null. |
Set.mapIndexedNotNull() returns value of type List
.
Using mapIndexedNotNull() to transform a set of integers by adding their indices to each element, and filtering out null results.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val indexed = numbers.mapIndexedNotNull { index, value -> if (index % 2 == 0) index + value else null }
println(indexed)
}
[1, 5, 9]
Using mapIndexedNotNull() to transform a set of strings by concatenating their indices to each string, and filtering out null results.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val indexedStrings = strings.mapIndexedNotNull { index, value -> if (value.length > 3) "$index: $value" else null }
println(indexedStrings)
}
[2: three]
Using mapIndexedNotNull() to transform a set of custom objects by including their indices in the transformation, and filtering out null results.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val indexedPeople = people.mapIndexedNotNull { index, person -> if (person.age > 30) "$index: ${person.name}, ${person.age}" else null }
println(indexedPeople)
}
[2: Charlie, 35]
In this Kotlin tutorial, we learned about mapIndexedNotNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.