'Create List<Object> from List<List<Object>> in kotlin
I have List<List> and I want to create List where I have all cars from List<List>. There is any way in Kotlin to create that (using map or something)? I don't want to create new list and add items in loops
Solution 1:[1]
tl;dr List.flatten()
Let's say your List<List<Car>> is called carLists, then you can simply call val cars: List<Car> = carLists.flatten() if you want to have a single list containing all the cars from the list of lists of cars.
Code only:
val carLists: List<List<Car>> = … // created or received
val cars = carLists.flatten()
Solution 2:[2]
val listOfLists: List<List<Int>> = listOf(listOf(1, 2, 3), listOf(4, 5))
One way would be to use flatten function. This function just flattens the inner lists
val flatten: List<Int> = listOfLists.flatten() //[1, 2, 3, 4, 5]
But if you need to do some transformation as well as flattening the list then you can do it with flatMap():
val flatMap: List<Int> = listOfLists.flatMap { it.map { it*2 } } //[2, 4, 6, 8, 10]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Saeed Entezari |
