Initialize a List of Lists in Kotlin
This article explores different ways to initialize a List of Lists in Kotlin.
1. Using List Constructor
The standard solution to initialize a List of Lists is using the List or MutableList constructor. This is demonstrated below:
|
1 2 3 4 5 6 |
fun main() { val M = 3 val listOfLists: MutableList<MutableList<Int>> = MutableList(M) { mutableListOf<Int>() } println(listOfLists) } |
Output:
[[], [], []]
Here’s a slight variation of the above approach to initialize the list with default values:
|
1 2 3 4 5 6 |
fun main() { val M = 3 val listOfLists: MutableList<MutableList<Int>> = MutableList(M) { MutableList<Int>(M) {0} } listOfLists.forEach(::println) } |
Output:
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
2. Using listOf() function
We can declare a list using the listOf() function. To initialize a List of Lists in a single line, use the listOf() function like below:
|
1 2 3 4 5 6 7 8 9 |
fun main() { val listOfLists = listOf( listOf(1, 2, 3), listOf(4, 5, 6), listOf(6, 7, 8) ) listOfLists.forEach(::println) } |
Output:
[1, 2, 3]
[4, 5, 6]
[6, 7, 8]
We can also use the mutableListOf() function to get a mutable list. After getting the mutable instance, we can pass a new list instance to the add() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val listOfLists: MutableList<MutableList<Int>> = mutableListOf() val M = 3 val N = 3 for (i in 0 until M) { listOfLists.add(MutableList(N) { 0 }) } listOfLists.forEach(::println) } |
Output:
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
3. Using map() function
Another plausible way is to use the map() function to generate a List of Lists, as demonstrated below:
|
1 2 3 4 5 6 7 |
fun main() { val M = 3 val N = 3 val listOfLists = (1..M).map { _ -> (1..N).map { 0 } } listOfLists.forEach(::println) } |
Output:
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
That’s all about initializing a List of Lists in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)