Kotlin one list to another

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

Читайте также:  Html символы конца строки

Источник

Collection transformation operations

The Kotlin standard library provides a set of extension functions for collection transformations. These functions build new collections from existing ones based on the transformation rules provided. In this page, we’ll give an overview of the available collection transformation functions.

Map

The mapping transformation creates a collection from the results of a function on the elements of another collection. The basic mapping function is map() . It applies the given lambda function to each subsequent element and returns the list of the lambda results. The order of results is the same as the original order of elements. To apply a transformation that additionally uses the element index as an argument, use mapIndexed() .

If the transformation produces null on certain elements, you can filter out the null s from the result collection by calling the mapNotNull() function instead of map() , or mapIndexedNotNull() instead of mapIndexed() .

When transforming maps, you have two options: transform keys leaving values unchanged and vice versa. To apply a given transformation to keys, use mapKeys() ; in turn, mapValues() transforms values. Both functions use the transformations that take a map entry as an argument, so you can operate both its key and value.

Zip

Zipping transformation is building pairs from elements with the same positions in both collections. In the Kotlin standard library, this is done by the zip() extension function.

When called on a collection or an array with another collection (or array) as an argument, zip() returns the List of Pair objects. The elements of the receiver collection are the first elements in these pairs.

If the collections have different sizes, the result of the zip() is the smaller size; the last elements of the larger collection are not included in the result.

zip() can also be called in the infix form a zip b .

You can also call zip() with a transformation function that takes two parameters: the receiver element and the argument element. In this case, the result List contains the return values of the transformation function called on pairs of the receiver and the argument elements with the same positions.

When you have a List of Pair s, you can do the reverse transformation – unzipping – that builds two lists from these pairs:

  • The first list contains the first elements of each Pair in the original list.
  • The second list contains the second elements.
Читайте также:  One block map java

To unzip a list of pairs, call unzip() .

Associate

Association transformations allow building maps from the collection elements and certain values associated with them. In different association types, the elements can be either keys or values in the association map.

The basic association function associateWith() creates a Map in which the elements of the original collection are keys, and values are produced from them by the given transformation function. If two elements are equal, only the last one remains in the map.

For building maps with collection elements as values, there is the function associateBy() . It takes a function that returns a key based on an element’s value. If two elements’ keys are equal, only the last one remains in the map.

associateBy() can also be called with a value transformation function.

Another way to build maps in which both keys and values are somehow produced from collection elements is the function associate() . It takes a lambda function that returns a Pair : the key and the value of the corresponding map entry.

Note that associate() produces short-living Pair objects which may affect the performance. Thus, associate() should be used when the performance isn’t critical or it’s more preferable than other options.

An example of the latter is when a key and the corresponding value are produced from an element together.

Here we call a transform function on an element first, and then build a pair from the properties of that function’s result.

Flatten

If you operate nested collections, you may find the standard library functions that provide flat access to nested collection elements useful.

The first function is flatten() . You can call it on a collection of collections, for example, a List of Set s. The function returns a single List of all the elements of the nested collections.

Another function – flatMap() provides a flexible way to process nested collections. It takes a function that maps a collection element to another collection. As a result, flatMap() returns a single list of its return values on all the elements. So, flatMap() behaves as a subsequent call of map() (with a collection as a mapping result) and flatten() .

String representation

If you need to retrieve the collection content in a readable format, use functions that transform the collections to strings: joinToString() and joinTo() .

Читайте также:  Цвет ссылок

joinToString() builds a single String from the collection elements based on the provided arguments. joinTo() does the same but appends the result to the given Appendable object.

When called with the default arguments, the functions return the result similar to calling toString() on the collection: a String of elements’ string representations separated by commas with spaces.

To build a custom string representation, you can specify its parameters in function arguments separator , prefix , and postfix . The resulting string will start with the prefix and end with the postfix . The separator will come after each element except the last.

For bigger collections, you may want to specify the limit – a number of elements that will be included into result. If the collection size exceeds the limit , all the other elements will be replaced with a single value of the truncated argument.

Finally, to customize the representation of elements themselves, provide the transform function.

Источник

Transforming Kotlin Collections – Functions with Examples

Whether you’re mapping the API response model or sorting, filtering, and manipulating Kotlin collections; these functions are very useful.

More on Kotlin

Kotlin Data Objects

Kotlin data objects just landed in with the version 1.7.20 as an experimental feature. We’ll look at how they are helpful.

Jetpack Compose Side Effects – With Examples

Recompositions and states are the main parts of Jetpack Compose. We’ll use Jetpack Compose Side Effects API’s and inspect each method.

Kotlin Coroutines: A Detailed Introduction

Kotlin Coroutines is an async task library for Kotlin language. It makes asynchronous code easier to write and read.

Using Azure Boards for Mobile App Development

Learn how to effectively use Azure Boards with Appcircle for mobile app development, strategies for issue tracking and management.

Streamline Project Integration and Test Automation with Repeato and Appcircle

Efficiently integrate and automate your software projects with Repeato and Appcircle. Discover the benefits!

Multi-Layered Team Management in Mobile DevOps

Learn how multi-layered team management can help enterprises streamline their mobile DevOps processes with Appcircle.

Resigning Binaries Made Easy with Appcircle

Resigning binaries made easy! Learn how to resign iOS and Android binaries with this step-by-step guide for app publishers.

Subscribe to Appcircle Circle

A bi-weekly newsletter for developers covering mobile development articles, CI/CD tips and trick and cool projects.

Источник

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