Flatten a List of Lists in Kotlin
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:
|
1 2 3 4 5 6 7 |
fun main() { val listOfLists = (1.. 3).map { i -> (1..4).map { i } } println("Original List: $listOfLists") val flattenedList = listOfLists.flatten() println("Flattened List: $flattenedList") } |
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:
|
1 2 3 4 5 6 7 |
fun main() { val listOfLists = (1.. 3).map { i -> (1..4).map { i } } println("Original List: $listOfLists") val flattenedList = listOfLists.flatMap { it } println("Flattened List: $flattenedList") } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun <T> flatten(listOfLists: List<List<T>>): List<T> { val result: MutableList<T> = mutableListOf() listOfLists.forEach { result.addAll(it) } return result } fun main() { val listOfLists = (1.. 3).map { i -> (1..4).map { i } } println("Original List: $listOfLists") val flattenedList = flatten(listOfLists) println("Flattened List: $flattenedList") } |
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:
|
1 2 3 4 5 6 7 |
fun main() { val listOfLists = (1.. 3).map { i -> (1..4).map { i } } println("Original List: $listOfLists") val flattenedList = listOfLists.reduce { x, y -> x + y } println("Flattened List: $flattenedList") } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)