Kotlin Program to Convert List (ArrayList) to Array and Vice-Versa

In this program, you'll learn to convert a list to an array using toArray() and array to list using asList() in Kotlin.

Example 1: Convert list to array

import java.util.*

fun main(args: Array<String>) {

    val list = ArrayList<String>()
    list.add("a")
    list.add("b")

    val array = arrayOfNulls<String>(list.size)
    list.toArray(array)

    println(Arrays.toString(array))

}

When you run the program, the output will be:

[a, b]

In the above program, we've an array list of strings list. To convert the list to an array, first we created a string array named array with size equals to list.size().

Then, we simply used list's toArray() method to convert the list items to array items.


Example 2: Convert Array to list

import java.util.*

fun main(args: Array<String>) {

    val array = arrayOf("a", "b")
    val list = Arrays.asList(*array)

    println(list)

}

When you run the program, the output will be:

[a, b]

In the above program, we've an array of strings array. To convert the array to a list, we used Arrays's asList() method and stored it in the list, list.

Here's the equivalent Java code: Java program to convert list to array and vice-versa.