Home > Net >  how to create mutablelistof() of many mutablelistof()?
how to create mutablelistof() of many mutablelistof()?

Time:11-15

I am trying to add mutable lists in other mutable lists
but i dont know how to do it.

I tried mutablelist of mutablelist but not working.

CodePudding user response:

Before reading my answer I suggest you to read Plus and minus operators and try to figure it out yourself.

If you're still having trouble understanding here are samples of the operations you can do with collections such as Lists.

Adding multiple lists to one list:

fun main() {
    val listA = mutableListOf(1, 2, 3)
    val listB = mutableListOf(3, 5, 6)
    
    val listOfLists = mutableListOf(listA, listB)
    println(listOfLists)
}

results in:

[[1, 2, 3], [3, 5, 6]]

Combining multiple lists in one list:

fun main() {
    val listA = mutableListOf(1, 2, 3)
    val listB = mutableListOf(3, 5, 6)
    
    val combinedLists = mutableListOf(listA   listB)
    println(combinedLists)
}

which results in:

[[1, 2, 3, 3, 5, 6]]

Substracting one list from another:

fun main() {
    val listA = mutableListOf(1, 2, 3)
    val listB = mutableListOf(3, 5, 6)
    
    val substractedLists = mutableListOf(listA - listB)
    println(substractedLists)
}

which results in:

[[1, 2]]

CodePudding user response:

You can add a mutableList using add function as below.

val a = mutableListOf(1, 2)
val b = mutableListOf(2, 3)
val c = mutableListOf(a)
c.add(b)
val d : MutableList<MutableList<Int>> = mutableListOf()
d.add(a)
d.add(b)
println(d)
  • Related