Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of lists in kotlin?

Tags:

kotlin

How do I create a list of lists?

I have a mutable list of ints:

val rsrpList = mutableListOf<Int>()

Now I am trying to create a list of lists, like this:

val rsrpList = mutableListOf<Int>()
val rsrqList = mutableListOf<Int>()
val levelList = mutableListOf<Int>()

val listoflists = List<List<Int>>
listoflists.add(rsrpList)
listoflists.add(rsrqList)
listoflists.add(levelList)

but I know this is wrong, because I'm adding a list one at a time, instead of a list of lists. How would I do this?

like image 214
rickster26ter1 Avatar asked Sep 20 '25 10:09

rickster26ter1


1 Answers

You can do this with the Kotlin Standard Library. Both List and MutableList can be created to a specific size (3 in this case) and specify a lambda that will initialize each value.

val listOfList = MutableList(3) { mutableListOf<Int>() }

Or:

val listOfList = List(3) { mutableListOf<Int>() }

Update: To initialize a List with precreated lists:

val listOfList = listOf(list1, list2, list3)

Or in your specific case:

val listOfList = listOf(rsrpList, rsrqList, levelList)

And in both cases you can replace listOf with mutableListOf if you want a mutable list as the main type.

like image 79
Todd Avatar answered Sep 22 '25 03:09

Todd