How to copy list kotlin

How to clone or copy a list in Kotlin?

It doesn’t matter which variable you use to add elements to, the list will contain a new element afterwards. Example — Using toList() toList() is the basic method which can convert a collection into a list.

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.

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.

Читайте также:  Бесконечный цикл python async

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.

Output

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

How to clone or copy a list in kotlin, I would use the toCollection () extension method: val original = listOf («A», «B», «C») val copy = original.toCollection (mutableListOf ()) This will create a new MutableList and then add each element of the original to the newly-created list. The inferred type here will be MutableList. Usage exampleval selectedSeries = series.toMutableList()Feedback

How to clone or copy a 2d list in kotlin

In your case peopleAtBlock2 is a shallow copy of peopleAtBlock1 , which means they reference the same objects. so when you change value of an object in peopleAtBlock1 , its reflected in peopleAtBlock2 also.

In order to solve this you will have to create a deep copy of peopleAtBlock1. recommended way to do this is to use serialization. that is first you serialize the original data and then create a copy by de serializing.

there are better ways of doing this but a quick and easy way is to use JSON serialization, which can be done by following the below steps

First add dependency for Gson in your project as

implementation 'com.google.code.gson:gson:2.8.8' 

Now move Person class outside the function, Gson doesn’t work with local classes

Finally you can create a deep copy as

val type = object : TypeToken>()<>.type val json = Gson().toJson(peopleAtBlock1, type) val peopleAtBlock2 = Gson().fromJson>(json, type) 
fun Person.deepCopy(): Person = copy(friends = friends.map < it.deepCopy() >) val peopleAtBlock2 = peopleAtBlock1.map

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.

How to make copy of MutableList in Kotlin?

Yes, in java and kotlin almost everything is being passed as reference. But in kotlin you have compile-time verified ability to make any MutableList immutable — just change method argument type from MutableList to List

When you add values to visited they will be added to the argument of your function (i.e. are also visible outside the function). Also, v and visited are pointing to the same object . It doesn’t matter which variable you use to add elements to, the list will contain a new element afterwards. The statement val v = visited does not create any copy . For copying a list you can do visited.toList() which under the hood basically maps to a call of ArrayList(visited) .

How to clone or copy a 2d list in kotlin, following from here below provided for the test case @Test fun testKotlinArrayCopy() < data class Person(val name: String, var friends: List, var isHungry: Boolean = false)

Clone a object in kotlin

You never create a copy of a state object.

This call creates another SwitchClone with values identical to copyDevice itself.

val state = copyDevice.copy(state = copyDevice.state) 

copy() only creates a shallow copy, which means all of your objects, in that case c , copyDevice and state point to the same c.state .

You need to explicitly create a deep copy (depending on what properties are mutable) of state object and assign it to copyDevice.state field.

For Kotlin when using the Kotlin Data Class data class you get a function called copy() for you. But If your Class is not a Data Class and your project has Gson and you want to copy the whole object ( probably edit after getting it ), Then if all those conditions are true then this is a solution. This is also a DeepCopy. ( For a data Class you can use the function copy() ).

Then if you are using Gson in your project. Add the function copy() :

If you want to install Gson then get the latest version here.

The copy() did not solve my purpose. However clone() did. I added the following line in my code and it worked as I desired.

How to clone object in Kotlin?, For a data class, you can use the compiler-generated copy () method. Note that it will perform a shallow copy. To create a copy of a collection, use the toList () or toSet () methods, depending on the collection type you need. These methods always create a new copy of a collection; they also perform a shallow …

Источник

Создание коллекций

()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/list-of.html), [`setOf ()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/set-of.html), [`mutableListOf ()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/mutable-list-of.html), [`mutableSetOf ()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/mutable-set-of.html). If you provide a comma-separated list of collection elements as arguments, the compiler detects the element type automatically. When creating empty collections, specify the type explicitly. —>

Самый распространённый способ создать коллекцию — использовать функции listOf() , setOf() , mutableListOf() , mutableSetOf() . Этим функциям в качестве аргументов можно передать элементы, разделяя их запятой. В этом случае тип коллекции указывать не обязательно — компилятор сам его определит. Если же вы хотите создать пустую коллекцию, то её тип необходимо указывать явно.

val numbersSet = setOf("one", "two", "three", "four") val emptySet = mutableSetOf() 

Таким же образом создаются и ассоциативные списки — при помощи функций mapOf() и mutableMapOf() . Ключи и значения ассоциативного списка передаются как объекты Pair (обычно создаются с помощью инфиксной функции to ).

val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1) 

Обратите внимание, что нотация to создаёт недолговечный объект Pair , поэтому рекомендуется использовать его только в том случае, если производительность не критична. Чтобы избежать чрезмерного использования памяти, используйте альтернативные способы. Например, вы можете создать MutableMap и заполнить его с помощью операций записи. Функция apply() поможет создать плавную инициализацию.

val numbersMap = mutableMapOf() .apply

Пустая коллекция

Существуют функции для создания пустых коллекций: emptyList() , emptySet() и emptyMap() . При создании пустой коллекции вы должны явно указывать тип элементов, которые будет содержать коллекция.

Функция-инициализатор для списков

У списков есть конструктор, принимающий размер списка и функцию-инициализатор, которая определяет значение элементов на основе их индексов.

fun main() < val doubled = List(3, < it * 2 >) // или MutableList, если вы хотите изменять содержимое println(doubled) // [0, 2, 4] > 

Конструкторы конкретных типов

Чтобы создать коллекцию конкретного типа, например, ArrayList или LinkedList , вы можете использовать их конструкторы. Аналогичные конструкторы доступны и для реализаций Set и Map .

val linkedList = LinkedList(listOf("one", "two", "three")) val presizedSet = HashSet(32) 

Копирование коллекции

Если вам требуется создать новую коллекцию, но с элементами из существующей коллекции, то вы можете её скопировать. Операции копирования из стандартной библиотеки создают неполные копии коллекций — со ссылками на исходные элементы. Поэтому изменение, внесённое в элемент коллекции, будет применено ко всем его копиям.

Функции копирования коллекций, такие как toList() , toMutableList() , toSet() и другие, фиксируют состояние коллекции в определённый момент времени. Результат их выполнения — новая коллекция, но с элементами из исходной коллекции. Если вы добавите или удалите элементы из исходной коллекции, это не повлияет на копии. Копии также могут быть изменены независимо от источника.

fun main() < val sourceList = mutableListOf(1, 2, 3) val copyList = sourceList.toMutableList() val readOnlyCopyList = sourceList.toList() sourceList.add(4) println("Copy size: $") // 3 //readOnlyCopyList.add(4) // ошибка компиляции println("Read-only copy size: $") // 3 > 

Эти функции также можно использовать для преобразования типа коллекции, например, для создания множества из списка или наоборот.

В качестве альтернативы вы можете создать новую ссылку на тот же экземпляр коллекции. Новую ссылку можно создать, инициализировав новую переменную для коллекции и записав в нее существующую коллекцию. Однако, изменив новую коллекцию, изменения отразятся во всех ссылках на эту коллекцию.

Подобная инициализация может использоваться для того, чтобы ограничить доступ на изменение коллекции. Например, вы создаёте ссылку List на основе MutableList , если вы попытаетесь изменить коллекцию с помощью этой ссылки, то компилятор выдаст ошибку.

fun main() < val sourceList = mutableListOf(1, 2, 3) val referenceList: List= sourceList //referenceList.add(4) // ошибка компиляции sourceList.add(4) println(referenceList) // показывает текущее состояние sourceList - [1, 2, 3, 4] > 

Вызов вспомогательных функций

Коллекции могут создаваться в результате выполнения операций над другими коллекциями. Например, функция filter создаёт новый список элементов, соответствующих заданному фильтру:

fun main() < val numbers = listOf("one", "two", "three", "four") val longerThan3 = numbers.filter < it.length >3 > println(longerThan3) // [three, four] > 

Существуют функции, которые преобразуют исходные элементы и возвращают новый список с результатом. Например, функция map :

fun main() < val numbers = setOf(1, 2, 3) println(numbers.map < it * 3 >) // [3, 6, 9] println(numbers.mapIndexed < idx, value ->value * idx >) // [0, 2, 6] > 

Или функция associateWith() , которая создаёт ассоциативный список:

Более подробная информация о таких функциях находится в разделе Операции коллекций.

Источник

Clone a list in Kotlin

This article explores different ways to clone a list in Kotlin.

1. Using Copy Constructor

A simple and efficient solution is to use a copy constructor to clone a list, which creates a new object as a copy of an existing object.

2. Using addAll() function

You can also use the addAll() function that appends all the given list elements at the end of a new list.

This can be shortened using the apply() function:

3. Using toCollection() function

Another solution is to use the toCollection() function, which appends all elements to the given destination collection.

4. Using mutableListOf() function

You can also use the toList() or toMutableList() function to create a copy of a collection. Although, there is no official documentation that guarantees that this function returns a new copy of the list.

5. Implement the Cloneable Interface

If you’re dealing with a list of objects, you can have the class implement the Cloneable interface and override its clone() function.

6. Using Data class

If your list is storing objects of a data class, you can use the copy() function derived by the compiler.

That’s all about cloning a list in Kotlin.

Average rating 5 /5. Vote count: 32

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂

This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it

Источник

Оцените статью