The mapIndexedTo() extension function in Kotlin applies the given transform function to each element and its index in the original set, and appends the results to the given destination.
The syntax of Set.mapIndexedTo() extension function is:
fun <T, R, C : MutableCollection<in R>> Set<T>.mapIndexedTo(destination: C, transform: (index: Int, T) -> R): C
This mapIndexedTo() extension function of Set applies the given transform function to each element and its index in the original collection and appends the results to the given destination.
Parameter | Optional/Required | Description |
---|---|---|
destination | required | The collection to which the results will be appended. |
transform | required | A function that takes an index and an element, and returns the transformed result. |
Set.mapIndexedTo() returns value of type C
.
Using mapIndexedTo() to transform a set of integers by adding their indices to each element, and appending them to a list.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val destination = mutableListOf<Int>()
numbers.mapIndexedTo(destination) { index, value -> index + value }
println(destination)
}
[1, 3, 5, 7, 9]
Using mapIndexedTo() to transform a set of strings by concatenating their indices to each string, and appending them to a list.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val destination = mutableListOf<String>()
strings.mapIndexedTo(destination) { index, value -> "$index: $value" }
println(destination)
}
[0: one, 1: two, 2: three]
Using mapIndexedTo() to transform a set of custom objects by including their indices in the transformation, and appending them to a list.
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 destination = mutableListOf<String>()
people.mapIndexedTo(destination) { index, person -> "$index: ${person.name}, ${person.age}" }
println(destination)
}
[0: Alice, 30, 1: Bob, 25, 2: Charlie, 35]
In this Kotlin tutorial, we learned about mapIndexedTo() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.