How to use the flatten method of the ArrayList in Kotlin
Overview
Let’s say we have a list containing the list type as an element. We can use the flatten method to create a new list containing all the sub-list elements in this scenario.
Syntax
fun <T> Iterable<Iterable<T>>.flatten(): List<T>
Arguments
This method doesn’t take any arguments.
Return value
This method returns a new list containing all the elements of the sublist of the list on which this method is invoked.
Code example
The code written below demonstrates how we use the flatten method:
fun main() {var list = arrayListOf(listOf(1,2), listOf(3,4))println("The ArrayList is $list")val newList = list.flatten()println("The flattened list is $newList")}
Code explanation
-
Line 3: We create a new ArrayList with the name
list, using thearrayListOfmethod. We pass two lists,listOf(1,2) and listOf(3,4), as arguments to thearrayListOfmethod. Hence, we get anArrayListwith two list elements as the elements of thelist. -
Line 6: We use the
flattenmethod to get a newlistcontaining all the elements of the sub-list that are present in thelist. In our case, the list elements are[1,2]and[3,4]. These are flattened to1,2,3,4and returned as a new list. Hence, we get[1,2,3,4]as a result.