Kotlin list add value

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

Источник

Операции записи коллекций

Изменяемые коллекции поддерживают операции, изменяющие её содержимое, например, операции по добавлению и удалению элементов. В этом разделе описаны операции записи, доступные для всех реализаций MutableCollection . Более конкретные операции, доступные для List и Map , описаны в разделах List: специфичные операции и Map: специфичные операции.

Добавление элементов

Чтобы добавить один элемент в список или множество ( Set ), используйте функцию add() . Указанный объект будет добавлен в конец коллекции.

Функция addAll() добавляет все элементы из переданного в качестве аргумента объекта в список или множество. Аргументом может быть Iterable , Sequence , или Array . Типы объекта-получателя и аргумента могут быть разными, например, вы можете добавить все элементы из Set в List .

При вызове к списку addAll() добавляет новые элементы в том же порядке, в котором они находятся в коллекции-аргументе. Вы также можете передать addAll() позицию, в которую будет вставлен первый элемент из коллекции-аргумента. За ним последуют другие элементы из коллекции-аргумента, сдвигая элементы коллекции-получателя в конец.

Вы также можете добавлять элементы, используя in-place версию оператора plus — plusAssign ( += ). При применении к изменяемой коллекции += добавляет второй операнд (элемент или другую коллекцию) в конец коллекции.

Удаление элементов

Чтобы удалить элемент из изменяемой коллекции, используйте функцию remove() . Она принимает значение элемента в качестве аргумента и удаляет из коллекции одно вхождение этого значения.

Для одновременного удаления нескольких элементов существуют следующие функции:

  • removeAll() — удаляет все элементы, присутствующие в коллекции-аргументе. В качестве альтернативы вы можете вызвать её с предикатом; в этом случае функция удаляет все элементы, для которых предикат возвращает true .
  • retainAll() — противоположность removeAll() : удаляет все элементы кроме тех, что находятся в коллекции-аргументе. При использовании с предикатом она оставляет только те элементы, которые ему соответствуют.
  • clear() — удаляет все элементы из списка, оставляя его пустым.
fun main() < val numbers = mutableListOf(1, 2, 3, 4) println(numbers) // [1, 2, 3, 4] numbers.retainAll < it >= 3 > println(numbers) // [3, 4] numbers.clear() println(numbers) // [] val numbersSet = mutableSetOf("one", "two", "three", "four") numbersSet.removeAll(setOf("one", "two")) println(numbersSet) // [three, four] > 

Еще один способ для удаления элементов из коллекции — оператор minusAssign ( -= ) — это in-place версия оператора minus . Второй аргумент может быть либо одним элементом, либо другой коллекцией. Если второй аргумент — это элемент, то оператор -= удалит первое вхождение этого элемента. Если же второй аргумент — это коллекция, то будут удалены все вхождения её элементов. Например, если список содержит повторяющиеся элементы, то они все будут удалены. Второй операнд может содержать элементы, которых нет в коллекции. Такие элементы не влияют на выполнение операции.

Обновление элементов

Списки и ассоциативные списки также предоставляют операции для обновления элементов. Они описаны в разделах List: специфичные операции и Map: специфичные операции. Для Set обновление элементов не имеет смысла, поскольку фактически он удаляет элемент и добавляет другой.

© 2015—2023 Open Source Community

Источник

Collection write operations

Mutable collections support operations for changing the collection contents, for example, adding or removing elements. On this page, we’ll describe write operations available for all implementations of MutableCollection . For more specific operations available for List and Map , see List-specific Operations and Map Specific Operations respectively.

Adding elements

To add a single element to a list or a set, use the add() function. The specified object is appended to the end of the collection.

addAll() adds every element of the argument object to a list or a set. The argument can be an Iterable , a Sequence , or an Array . The types of the receiver and the argument may be different, for example, you can add all items from a Set to a List .

When called on lists, addAll() adds new elements in the same order as they go in the argument. You can also call addAll() specifying an element position as the first argument. The first element of the argument collection will be inserted at this position. Other elements of the argument collection will follow it, shifting the receiver elements to the end.

You can also add elements using the in-place version of the plus operator — plusAssign ( += ) When applied to a mutable collection, += appends the second operand (an element or another collection) to the end of the collection.

Removing elements

To remove an element from a mutable collection, use the remove() function. remove() accepts the element value and removes one occurrence of this value.

For removing multiple elements at once, there are the following functions :

  • removeAll() removes all elements that are present in the argument collection. Alternatively, you can call it with a predicate as an argument; in this case the function removes all elements for which the predicate yields true .
  • retainAll() is the opposite of removeAll() : it removes all elements except the ones from the argument collection. When used with a predicate, it leaves only elements that match it.
  • clear() removes all elements from a list and leaves it empty.

fun main() < //sampleStart val numbers = mutableListOf(1, 2, 3, 4) println(numbers) numbers.retainAll < it >= 3 > println(numbers) numbers.clear() println(numbers) val numbersSet = mutableSetOf(«one», «two», «three», «four») numbersSet.removeAll(setOf(«one», «two»)) println(numbersSet) //sampleEnd >

Another way to remove elements from a collection is with the minusAssign ( -= ) operator – the in-place version of minus . The second argument can be a single instance of the element type or another collection. With a single element on the right-hand side, -= removes the first occurrence of it. In turn, if it’s a collection, all occurrences of its elements are removed. For example, if a list contains duplicate elements, they are removed at once. The second operand can contain elements that are not present in the collection. Such elements don’t affect the operation execution.

Updating elements

Lists and maps also provide operations for updating elements. They are described in List-specific Operations and Map Specific Operations. For sets, updating doesn’t make sense since it’s actually removing an element and adding another one.

Источник

Читайте также:  Body background image css height
Оцените статью