English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program converts a list (ArrayList) to an Array, Array to ArrayList

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to use toArray() to convert a list to an array in Kotlin, and use asList() to convert an array to a list.

Example1: Convert an array list to an array

fun main(args: Array<String>) {
    //Vowel array list
    val vowels_list: List<String> = listOf("a", "e", "i", "o", "u")
    
    //Convert an ArrayList to an array
    val vowels_array: Array<String> = vowels_list.toTypedArray()
    
    //Print the elements of the array
    vowels_array.forEach { System.out.print(it) }
}

Output Result

aeiou

In the above program, we define an array list called vowels_list. To convert an array list to an array, we use the toTypedArray() method.

Finally, use forEach() loop to print the elements of the array.

Example2: Convert an array to an array list

fun main(args: Array<String>) {
    //Vowel array
    val vowels_array: Array<String> = arrayOf("a", "e", "i", "o", "u")
    
    //Convert Array to Array List
    val vowels_list: List<String> = vowels_array.toList()
    
    //Print Elements in the Array List
    vowels_list.forEach { System.out.print(it) }
}

Output Result

aeiou

To convert an array to an array list, we used the toList() method.

This is the equivalent Java code:Java Program to Convert Array List to Array.

Comprehensive Collection of Kotlin Examples