Kotlin List mapIndexed()
Syntax & Examples
Syntax of List.mapIndexed()
The syntax of List.mapIndexed() extension function is:
fun <T, R> Iterable<T>.mapIndexed( transform: (index: Int, T) -> R ): List<R>This mapIndexed() extension function of List returns a list containing the 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 named
list1containing the integers10, 20, 30. - We then apply the
mapIndexedfunction tolist1, which takes a lambda with two parameters:indexandvalue. - Within the lambda, we concatenate the index and value into a string format.
- The
mapIndexedfunction returns a new list containing the transformed elements. - The resulting list, containing strings representing each element along with its index, is stored in
result. - Finally, we print the value of
resultto standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(10, 20, 30);
val result = list1.mapIndexed { index, value -> "\$index: \$value" }
print(result);
}Output
[0: 10, 1: 20, 2: 30]
2 Example
In this example,
- We create a list named
list1containing the characters'a', 'p', 'p', 'l', 'e'. - We then apply the
mapIndexedfunction tolist1, which takes a lambda with two parameters:indexandvalue. - Within the lambda, we concatenate the index and value into a string format.
- The
mapIndexedfunction returns a new list containing the transformed elements. - The resulting list, containing strings representing each character along with its index, is stored in
result. - Finally, we print the value of
resultto standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "p", "p", "l", "e");
val result = list1.mapIndexed { index, value -> "\$index: \$value" }
print(result);
}Output
[0: a, 1: p, 2: p, 3: l, 4: e]
3 Example
In this example,
- We create a list named
list1containing the strings'apple', 'banana', 'cherry'. - We then apply the
mapIndexedfunction tolist1, which takes a lambda with two parameters:indexandvalue. - Within the lambda, we concatenate the index and value into a string format.
- The
mapIndexedfunction returns a new list containing the transformed elements. - The resulting list, containing strings representing each element along with its index, is stored in
result. - Finally, we print the value of
resultto standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry");
val result = list1.mapIndexed { index, value -> "\$index: \$value" }
print(result);
}Output
[0: apple, 1: banana, 2: cherry]
Summary
In this Kotlin tutorial, we learned about mapIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.