Home > Software design >  Create List<Object> from List<List<Object>> in kotlin
Create List<Object> from List<List<Object>> in kotlin

Time:04-26

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

CodePudding user response:

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()

CodePudding user response:

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]
  • Related