Kotlin List flatten()
Syntax & Examples
Syntax of List.flatten()
The syntax of List.flatten() extension function is:
fun <T> Iterable<Iterable<T>>.flatten(): List<T>
This flatten() extension function of List returns a single list of all elements from all collections in the given collection.
✐ Examples
1 Example
In this example,
- We create a list of lists named
list1
, where each inner list contains integers. - We use the
flatten()
function onlist1
to combine all elements from inner lists into a single list. - The flattened 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(listOf(1, 2), listOf(3, 4), listOf(5, 6))
val result = list1.flatten()
println(result)
}
Output
[1, 2, 3, 4, 5, 6]
2 Example
In this example,
- We create a list of lists named
list2
, where each inner list contains characters. - We use the
flatten()
function onlist2
to combine all elements from inner lists into a single list. - The flattened 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(listOf('a', 'b'), listOf('c', 'd'), listOf('e', 'f'))
val result = list2.flatten()
println(result)
}
Output
[a, b, c, d, e, f]
3 Example
In this example,
- We create a list of lists named
list3
, where each inner list contains strings. - We use the
flatten()
function onlist3
to combine all elements from inner lists into a single list. - The flattened 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(listOf("hello", "world"), listOf("goodbye", "moon"))
val result = list3.flatten()
println(result)
}
Output
[hello, world, goodbye, moon]
Summary
In this Kotlin tutorial, we learned about flatten() extension function of List: the syntax and few working examples with output and detailed explanation for each example.