The mapIndexed() extension function in Kotlin returns a list containing the results of applying the given transform function to each element and its index in the original set.
The syntax of Set.mapIndexed() extension function is:
fun <T, R> Set<T>.mapIndexed(transform: (index: Int, T) -> R): List<R>
This mapIndexed() extension function of Set returns a list containing the 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. |
Set.mapIndexed() returns value of type List
.
Using mapIndexed() to transform a set of integers by adding their indices to each element.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val indexed = numbers.mapIndexed { index, value -> index + value }
println(indexed)
}
[1, 3, 5, 7, 9]
Using mapIndexed() to transform a set of strings by concatenating their indices to each string.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val indexedStrings = strings.mapIndexed { index, value -> "$index: $value" }
println(indexedStrings)
}
[0: one, 1: two, 2: three]
Using mapIndexed() to transform a set of custom objects by including their indices in the transformation.
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.mapIndexed { index, person -> "$index: ${person.name}, ${person.age}" }
println(indexedPeople)
}
[0: Alice, 30, 1: Bob, 25, 2: Charlie, 35]
In this Kotlin tutorial, we learned about mapIndexed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.