Convert List of String to a String array in Kotlin
This post will discuss how to convert a list of strings to a string array in Kotlin.
1. Using toTypedArray() function
A simple solution to convert a list to a typed array is using the toTypedArray() function. The following solution demonstrates its usage by invoking the toTypedArray() function on List<String>, that results in an Array<String>.
|
1 2 3 4 5 6 |
fun main() { val cities = listOf("Washington, D.C.", "Los Angeles", "Seattle") val array = cities.toTypedArray() println(array.contentToString()) } |
Output:
[Washington, D.C., Los Angeles, Seattle]
2. Naive solution
A naive solution allocates storage for the destination string array, and iterate over the list of strings to copy each element to its correct position in the string array. This can be implemented as follows in Kotlin.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val cities = listOf("Washington, D.C.", "Los Angeles", "Seattle") // allocate storage for the string array val array = arrayOfNulls<String>(cities.size) // copy all the list elements to the string array for (i in array.indices) { array[i] = cities[i] } println(array.contentToString()) } |
Output:
[Washington, D.C., Los Angeles, Seattle]
That’s all about converting a List of String to an array of Kotlin String.
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 :)