This article explores different ways to flatten a List of Lists in Kotlin.

1. Using flatten() function

The standard solution to flatten a list in Kotlin is using the flatten() function. It returns a single list of all elements from all lists in the given list. The following code example shows invocation for this function:

Download Code

Output:

Original List: [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

2. Using flatMap() function

Another option is to use the flatMap() function that returns a single list of all elements yielded from the results of the transform function being invoked on each element of the original collection. The following code demonstrates its usage:

Download Code

Output:

Original List: [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

3. Using forEach() function

Another alternative is to use a foreach-construct or the forEach() function to add elements of each list into a new list. This logic would translate to the following code:

Download Code

Output:

Original List: [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

4. Using reduce() function

Finally, we can perform a reduction operation on the elements of the list using an associative accumulation function. This is demonstrated below:

Download Code

Output:

Original List: [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

That’s all about flattening a List of Lists in Kotlin.