Kotlin List flatMapTo()
Syntax & Examples
Syntax of List.flatMapTo()
The syntax of List.flatMapTo() extension function is:
fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo( destination: C, transform: (T) -> Iterable<R> ): C
This flatMapTo() extension function of List appends all elements yielded from results of transform function being invoked on each element of original collection, to the given destination.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing integers. - We create a mutable list named
destination
. - We use the
flatMapTo
function onlist1
with a transform function that returns a list containing each element and its double. - The flatMapped list is stored in
destination
. - 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 destination = mutableListOf<Int>()
val result = list1.flatMapTo(destination) { listOf(it, it * 2) }
println(result)
}
Output
[1, 2, 2, 4, 3, 6]
2 Example
In this example,
- We create a list named
list2
containing strings. - We create a mutable list named
destination
. - We use the
flatMapTo
function onlist2
with a transform function that returns a list containing each element and its reversed form. - The flatMapped list is stored in
destination
. - 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 destination = mutableListOf<String>()
val result = list2.flatMapTo(destination) { listOf(it, it.reversed()) }
println(result)
}
Output
[apple, elppa, banana, ananab, cherry, yrrehc]
3 Example
In this example,
- We create a list named
list3
containing strings. - We create a mutable list named
destination
. - We use the
flatMapTo
function onlist3
with a transform function that returns a list containing each element and its length. - The flatMapped list is stored in
destination
. - 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 destination = mutableListOf<String>()
val result = list3.flatMapTo(destination) { listOf(it, it.length.toString()) }
println(result)
}
Output
[hello, 5, world, 5]
Summary
In this Kotlin tutorial, we learned about flatMapTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.