Kotlin List flatMapIndexedTo()
Syntax & Examples
Syntax of List.flatMapIndexedTo()
The syntax of List.flatMapIndexedTo() extension function is:
fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapIndexedTo( destination: C, transform: (index: Int, T) -> Iterable<R> ): C
This flatMapIndexedTo() extension function of List appends all elements yielded from results of transform function being invoked on each element and its index in the original collection, to the given destination.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing strings. - We initialize an empty mutable list named
result
. - We apply the
flatMapIndexedTo
function onlist
to transform each element along with its index into a string in the formatindex: element
and append the results toresult
. - The resulting list is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry");
val result = mutableListOf<String>();
list.flatMapIndexedTo(result) { index, element -> listOf("$index: $element") };
println(result);
}
Output
[0: apple, 1: banana, 2: cherry]
2 Example
In this example,
- We create a list named
list
containing integers. - We initialize an empty mutable list named
result
. - We apply the
flatMapIndexedTo
function onlist
to transform each element along with its index into pairs of index and double of the element and append the results toresult
. - The resulting list is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(10, 20, 30);
val result = mutableListOf<Int>();
list.flatMapIndexedTo(result) { index, element -> listOf(index, element * 2) };
println(result);
}
Output
[0, 20, 1, 40, 2, 60]
3 Example
In this example,
- We create a list named
list
containing characters. - We initialize an empty mutable list named
result
. - We apply the
flatMapIndexedTo
function onlist
to transform each character along with its index into strings in the formatindex: character
andindex: uppercase character
, and append the results toresult
. - The resulting list is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c');
val result = mutableListOf<String>();
list.flatMapIndexedTo(result) { index, element -> listOf("$index: $element", "$index: ${element.toUpperCase()}") };
println(result);
}
Output
[0: a, 0: A, 1: b, 1: B, 2: c, 2: C]
Summary
In this Kotlin tutorial, we learned about flatMapIndexedTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.