Kotlin List mapIndexedTo()
Syntax & Examples
Syntax of List.mapIndexedTo()
The syntax of List.mapIndexedTo() extension function is:
fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapIndexedTo( destination: C, transform: (index: Int, T) -> R ): C
This mapIndexedTo() extension function of List applies the given transform function to each element and its index in the original collection and appends the results to the given destination.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list
containing elements1, 2, 3, 4, 5
. - We create a mutable destination list named
destination
. - We use the
mapIndexedTo()
function with an index and value. - We transform each element and index into a string format and append them 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.mapIndexedTo(destination) { index, value -> "Item \$index: \$value" }
println("Mapped list: \$result")
}
Output
Mapped list: [Item 0: 1, Item 1: 2, Item 2: 3, Item 3: 4, Item 4: 5]
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
mapIndexedTo()
function with an index and value. - We transform each character and its index into a string format and append them 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.mapIndexedTo(destination) { index, value -> "Index \$index: \$value" }
println("Mapped list: \$result")
}
Output
Mapped list: [Index 0: a, Index 1: b, Index 2: c]
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
mapIndexedTo()
function with an index and value. - We transform each string and its index into a string format and append them 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.mapIndexedTo(destination) { index, value -> "\$value is at index \$index" }
println("Mapped list: \$result")
}
Output
Mapped list: [apple is at index 0, banana is at index 1, cherry is at index 2]
Summary
In this Kotlin tutorial, we learned about mapIndexedTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.