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.
fun <T> Iterable<Iterable<T>>.flatten(): List<T>
This method doesn’t take any arguments.
This method returns a new list containing all the elements of the sublist of the list on which this method is invoked.
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") }
Line 3: We create a new ArrayList with the name list
, using the arrayListOf
method. We pass two lists, listOf(1,2) and listOf(3,4)
, as arguments to the arrayListOf
method. Hence, we get an ArrayList
with two list elements as the elements of the list
.
Line 6: We use the flatten
method to get a new list
containing all the elements of the sub-list that are present in the list
. In our case, the list elements are [1,2]
and [3,4]
. These are flattened to 1,2,3,4
and returned as a new list. Hence, we get [1,2,3,4]
as a result.
RELATED TAGS
CONTRIBUTOR
View all Courses