- List
- Parameters
- Properties
- size
- Functions
- contains
- containsAll
- get
- indexOf
- isEmpty
- iterator
- lastIndexOf
- listIterator
- subList
- Extension Properties
- indices
- lastIndex
- Extension Functions
- all
- any
- asIterable
- asReversed
- asSequence
- associate
- associateBy
- associateByTo
- associateTo
- associateWith
- associateWithTo
- binarySearch
- Collection transformation operations
- Map
- Zip
- Associate
- Flatten
- String representation
- Преобразование набора в список в Kotlin
- 1. Использование toList() функция
- 2. Использование конструктора копирования
- 3. Использование оператора спреда
- 4. Использование цикла
- 5. Использование addAll() функция
List
A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.
Parameters
E — the type of elements contained in the list. The list is covariant in its element type.
Properties
size
Returns the size of the collection.
Functions
contains
Checks if the specified element is contained in this collection.
containsAll
Checks if all elements in the specified collection are contained in this collection.
get
Returns the element at the specified index in the list.
indexOf
Returns the index of the first occurrence of the specified element in the list, or -1 if the specified element is not contained in the list.
isEmpty
Returns true if the collection is empty (contains no elements), false otherwise.
iterator
Returns an iterator over the elements of this object.
lastIndexOf
Returns the index of the last occurrence of the specified element in the list, or -1 if the specified element is not contained in the list.
listIterator
Returns a list iterator over the elements in this list (in proper sequence).
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified index.
subList
Returns a view of the portion of this list between the specified fromIndex (inclusive) and toIndex (exclusive). The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
Extension Properties
indices
Returns an IntRange of the valid indices for this collection.
lastIndex
Returns the index of the last item in the list or -1 if the list is empty.
Extension Functions
all
Returns true if all elements match the given predicate.
any
Returns true if collection has at least one element.
Returns true if at least one element matches the given predicate.
asIterable
Returns this collection as an Iterable.
asReversed
Returns a reversed read-only view of the original List. All changes made in the original list will be reflected in the reversed one.
asSequence
Creates a Sequence instance that wraps the original collection returning its elements when being iterated.
associate
Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.
associateBy
Returns a Map containing the elements from the given collection indexed by the key returned from keySelector function applied to each element.
Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.
associateByTo
Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function applied to each element of the given collection and value is the element itself.
Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function and and value is provided by the valueTransform function applied to elements of the given collection.
fun < T , K , V , M : MutableMap < in K , in V >> Iterable < T >. associateByTo (
destination : M ,
keySelector : ( T ) -> K ,
valueTransform : ( T ) -> V
) : M
associateTo
Populates and returns the destination mutable map with key-value pairs provided by transform function applied to each element of the given collection.
associateWith
Returns a Map where keys are elements from the given collection and values are produced by the valueSelector function applied to each element.
associateWithTo
Populates and returns the destination mutable map with key-value pairs for each element of the given collection, where key is the element itself and value is provided by the valueSelector function applied to that key.
binarySearch
Searches this list or its range for the provided element using the binary search algorithm. The list is expected to be sorted into ascending order according to the Comparable natural ordering of its elements, otherwise the result is undefined.
fun < T : Comparable < T >> List < T ? >. binarySearch (
element : T ? ,
fromIndex : Int = 0 ,
toIndex : Int = size
) : Int
Searches this list or its range for the provided element using the binary search algorithm. The list is expected to be sorted into ascending order according to the specified comparator, otherwise the result is undefined.
fun < T > List < T >. binarySearch (
element : T ,
comparator : Comparator < in T >,
fromIndex : Int = 0 ,
toIndex : Int = size
) : Int
Searches this list or its range for an element for which the given comparison function returns zero using the binary search algorithm.
fun < T > List < T >. binarySearch (
fromIndex : Int = 0 ,
toIndex : Int = size ,
comparison : ( T ) -> Int
) : Int
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.
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.
Преобразование набора в список в Kotlin
В этой статье рассматриваются различные способы преобразования набора в список с помощью Kotlin.
1. Использование toList() функция
Стандартный способ преобразования набора в список — использование toList() функция.
Он возвращает экземпляр неизменяемого списка. Чтобы получить изменяемый список, вы можете использовать toMutableList() функция.
2. Использование конструктора копирования
Мы можем использовать конструктор копирования, который может взять другой объект коллекции для создания нового списка, содержащего все элементы указанного набора.
3. Использование оператора спреда
Вы также можете использовать listOf() используя оператор Spread, добавляя к его реализации массива префикс * .
4. Использование цикла
Другое решение — создать пустой список и поместить в него каждый элемент указанного набора.
5. Использование addAll() функция
Вместо использования цикла for вы можете использовать addAll() чтобы добавить все элементы указанного набора в список.
Вот и все о преобразовании набора в список в Kotlin.
Средний рейтинг 5 /5. Подсчет голосов: 22
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно