Kotlin List flatMap()
Syntax & Examples
Syntax of List.flatMap()
The syntax of List.flatMap() extension function is:
fun <T, R> Iterable<T>.flatMap( transform: (T) -> Iterable<R> ): List<R>
This flatMap() extension function of List returns a single list of all elements yielded from results of transform function being invoked on each element of original collection.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing integers. - We apply the
flatMap
function onlist
to double each element and create a new list containing both the original element and its double. - The resulting list is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3);
val result = list.flatMap { listOf(it, it * 2) };
println(result);
}
Output
[1, 2, 2, 4, 3, 6]
2 Example
In this example,
- We create a list named
list
containing characters. - We apply the
flatMap
function onlist
to create a new list containing both the original character and its uppercase version. - The resulting list is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c');
val result = list.flatMap { listOf(it, it.toUpperCase()) };
println(result);
}
Output
[a, A, b, B, c, C]
3 Example
In this example,
- We create a list named
list
containing strings. - We apply the
flatMap
function onlist
to split each string into individual characters and create a new list containing all these characters. - The resulting list is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry");
val result = list.flatMap { it.toList() };
println(result);
}
Output
[a, p, p, l, e, b, a, n, a, n, a, c, h, e, r, r, y]
Summary
In this Kotlin tutorial, we learned about flatMap() extension function of List: the syntax and few working examples with output and detailed explanation for each example.