How to clone or copy a list in Kotlin?


A list is a type of collection in which data is stored in a sequential manner. We might come across a situation where the contents of one List have to be copied into another. In this article, we will see how to use Kotlin's built-in methods to clone a list.

Example - Using toList()

toList() is the basic method which can convert a collection into a list. We can use this method to clone an existing list too.

fun main(args: Array<String>) {
   val x = listOf(1,2,3,4,5,6,7,8,9)
   val copiedList=x.toList();
   println("Given collection: " +x)
   println("Clone list: " +copiedList)
}

Output

It will generate the following output

Given collection: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Clone list: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example - using toArray()

Cloning an existing collection can be done using the toArray() method.

fun main(args: Array<String>) {
   val array = arrayListOf("1", "2", "3", "4")
   val arrayCopy = array.toArray()
   print("The first element of the array: " +arrayCopy[0])
}

Output

In the above example, we are printing the array list using toArray(). We are printing the zeroth index value in the array.

The first element of the array: 1

Example - ArrayList()

Kotlin has a standard function called ArrayList() that can be used to copy one array into another. The following example demonstrates how to use it.

fun main(args: Array<String>) {
   val list = mutableListOf("a", "b", "c")
   val list2 = ArrayList(list)
   print(list2)
}

Output

The above piece of code will copy the mutable list "list" into another empty list "list2".

[a, b, c]

Updated on: 23-Nov-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements