Kotlin List.flatten() – Examples

Kotlin List.flatten()

The Kotlin List.flatten() function returns a single list of all elements from all collections in the given list.

Syntax

List.flatten()

Example 1

In this example,

  1. Take a list of lists.
  2. Call the flatten() function on the list. The function should return a single list with all the elements of inner lists as elements.

Program

fun main(args: Array<String>) {
    val list1 = listOf(
            listOf("a", "b"),
            listOf("c", "d", "e")
    )
    val result = list1.flatten()
    print(result)
}

Output

[a, b, c, d, e]

Example 2

In this example,

  1. Take a list of sets.
  2. Call the flatten() function on the list. The function should return a single list with all the elements of inner sets as elements.

Program

fun main(args: Array<String>) {
    val list1 = listOf(
            setOf("a", "b"),
            setOf("c", "d", "e")
    )
    val result = list1.flatten()
    print(result)
}

Output

[a, b, c, d, e]