Kotlin List flatMapIndexed()
Syntax & Examples
Syntax of List.flatMapIndexed()
The syntax of List.flatMapIndexed() extension function is:
fun <T, R> Iterable<T>.flatMapIndexed( transform: (index: Int, T) -> Iterable<R> ): List<R>
This flatMapIndexed() extension function of List returns a single list of all elements yielded from results of transform function being invoked on each element and its index in the original collection.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing integers. - We use the
flatMapIndexed
function onlist1
with a transform function that returns a list containing the index and value of each element. - The flatMapped list is stored in
result
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3)
val result = list1.flatMapIndexed { index, value -> listOf(index, value) }
println(result)
}
Output
[0, 1, 1, 2, 2, 3]
2 Example
In this example,
- We create a list named
list2
containing strings. - We use the
flatMapIndexed
function onlist2
with a transform function that returns a list containing the index and value formatted as strings. - The flatMapped list is stored in
result
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf("apple", "banana", "cherry")
val result = list2.flatMapIndexed { index, value -> listOf("$index: $value") }
println(result)
}
Output
[0: apple, 1: banana, 2: cherry]
3 Example
In this example,
- We create a list named
list3
containing strings. - We use the
flatMapIndexed
function onlist3
with a transform function that returns a list containing the reversed value of each string and its index. - The flatMapped list is stored in
result
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("hello", "world")
val result = list3.flatMapIndexed { index, value -> listOf(value.reversed(), index) }
println(result)
}
Output
[olleh, 0, dlrow, 1]
Summary
In this Kotlin tutorial, we learned about flatMapIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.