Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert mutable 2D array of pairs to a static 2D array in kotlin

How can I convert:
mutableListOf<MutableList<Pair<Int, Int>>>
To a:
Array<Array<Pair<Int,Int>>>

I’m pretty new in the language of Kotlin, I thought that I can loop for the entire 2D array and put the values in the new one, but I was wondering if there’s another faster solution

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I thought that I can loop for the entire 2D array and put the values in the new one

You can’t actually explicitly "loop". When you create an Array of non-null elements in Kotlin you have to specify the default value at each index. So all you have to do is specify each element of the list:

// suppose list is a MutableList<MutableList<Pair<Int, Int>>>
// create an array of list.size...
Array(list.size) { i ->
    // where the element at index i is another array with size "list[i].size"
    Array(list[i].size) { j -> 
        // and the element at index j of this array is "list[i][j]"
        list[i][j] 
    }
}

This is pretty much as fast as you can get in terms of execution time.

If you mean "fast" as in less typing, you can do:

list.map { it.toTypedArray() }.toTypedArray()

This first converts the inner lists to arrays, creating a List<Array<Pair<Int, Int>>>, and then converts that list to an array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading