Kotlin program to convert a list to Array

Kotlin program to convert a list to Array:

Sometimes we need to convert a list to an array in Kotlin. An array is fixed size, but lists are dynamic size. Not only this, they have many other differences. In this post, we will learn how to convert a Kotlin list to an array.

toTypedArray():

toTypedArray() method can be used to convert a list to array. This method returns a typed array that contains all the elements of the list.

This method allocates an array of size equal to the list and populates the array with the items of the list.

Kotlin program:

Below is the complete program that converts a list to array:

package com.company

fun main() {
    val wordsList: List<String> = listOf("one", "two", "three", "four", "five")

    val wordsArray = wordsList.toTypedArray()

    wordsArray.forEach { print("$it ") }
}

Here,

  • wordsList is the list of strings
  • We are converting this list to an array and storing that value in wordsArray.
  • The last line prints the content of the wordsArray by using a forEach loop.

It will print the output as like below: Kotlin convert list to array

Convert a number ArrayList to Array:

Let’s try to convert a number ArrayList to an Array. We can use the toTypedArray method as like the above example.

package com.company

fun main() {
    val numberList = ArrayList<Int>()
    numberList.add(1)
    numberList.add(2)
    numberList.add(3)
    numberList.add(4)

    val numberArray = numberList.toTypedArray()

    numberArray.forEach { print("$it ") }
}

It will print:

1 2 3 4

You might also like: