- MutableList
- Parameters
- Functions
- add
- addAll
- clear
- listIterator
- remove
- removeAll
- removeAt
- retainAll
- set
- subList
- Extension Properties
- indices
- lastIndex
- Extension Functions
- addAll
- all
- any
- asIterable
- asReversed
- asSequence
- associate
- associateBy
- associateByTo
- associateTo
- associateWith
- associateWithTo
- binarySearch
- binarySearchBy
- chunked
- Constructing collections
- Create with collection builder functions
- Empty collections
- Initializer functions for lists
- Concrete type constructors
- Copy
- Invoke functions on other collections
- Kotlin mutablelist from list
- Методы списков
- Получение части списка
- Изменяемые списки
MutableList
A generic ordered collection of elements that supports adding and removing elements.
Parameters
E — the type of elements contained in the list. The mutable list is invariant in its element type.
Functions
add
Adds the specified element to the end of this list.
Inserts an element into the list at the specified index.
addAll
Adds all of the elements of the specified collection to the end of this list.
Inserts all of the elements of the specified collection elements into this list at the specified index.
clear
Removes all elements from this collection.
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.
remove
Removes a single instance of the specified element from this collection, if it is present.
removeAll
Removes all of this collection’s elements that are also contained in the specified collection.
removeAt
Removes an element at the specified index from the list.
retainAll
Retains only the elements in this collection that are contained in the specified collection.
set
Replaces the element at the specified position in this list with the specified element.
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
addAll
Adds all elements of the given elements collection to this MutableCollection.
Adds all elements of the given elements sequence to this MutableCollection.
Adds all elements of the given elements array to this MutableCollection.
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 mutable view of the original mutable List. All changes made in the original list will be reflected in the reversed one and vice versa.
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 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
binarySearchBy
Searches this list or its range for an element having the key returned by the specified selector function equal to the provided key value using the binary search algorithm. The list is expected to be sorted into ascending order according to the Comparable natural ordering of keys of its elements. otherwise the result is undefined.
fun < T , K : Comparable < K >> List < T >. binarySearchBy (
key : K ? ,
fromIndex : Int = 0 ,
toIndex : Int = size ,
selector : ( T ) -> K ?
) : Int
chunked
Splits this collection into a list of lists each not exceeding the given size.
Splits this collection into several lists each not exceeding the given size and applies the given transform function to an each.
Constructing collections
The most common way to create a collection is with the standard library functions listOf() , setOf() , mutableListOf() , mutableSetOf() . 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.
The same is available for maps with the functions mapOf() and mutableMapOf() . The map’s keys and values are passed as Pair objects (usually created with to infix function).
Note that the to notation creates a short-living Pair object, so it’s recommended that you use it only if performance isn’t critical. To avoid excessive memory usage, use alternative ways. For example, you can create a mutable map and populate it using the write operations. The apply() function can help to keep the initialization fluent here.
Create with collection builder functions
Another way of creating a collection is to call a builder function – buildList() , buildSet() , or buildMap() . They create a new, mutable collection of the corresponding type, populate it using write operations, and return a read-only collection with the same elements:
val map = buildMap < // this is MutableMap, types of key and value are inferred from the `put()` calls below put("a", 1) put("b", 0) put("c", 4) > println(map) //
Empty collections
There are also functions for creating collections without any elements: emptyList() , emptySet() , and emptyMap() . When creating empty collections, you should specify the type of elements that the collection will hold.
Initializer functions for lists
For lists, there is a constructor-like function that takes the list size and the initializer function that defines the element value based on its index.
fun main() < //sampleStart val doubled = List(3, < it * 2 >) // or MutableList if you want to change its content later println(doubled) //sampleEnd >
Concrete type constructors
To create a concrete type collection, such as an ArrayList or LinkedList , you can use the available constructors for these types. Similar constructors are available for implementations of Set and Map .
Copy
To create a collection with the same elements as an existing collection, you can use copying functions. Collection copying functions from the standard library create shallow copy collections with references to the same elements. Thus, a change made to a collection element reflects in all its copies.
Collection copying functions, such as toList() , toMutableList() , toSet() and others, create a snapshot of a collection at a specific moment. Their result is a new collection of the same elements. If you add or remove elements from the original collection, this won’t affect the copies. Copies may be changed independently of the source as well.
These functions can also be used for converting collections to other types, for example, build a set from a list or vice versa.
Alternatively, you can create new references to the same collection instance. New references are created when you initialize a collection variable with an existing collection. So, when the collection instance is altered through a reference, the changes are reflected in all its references.
Collection initialization can be used for restricting mutability. For example, if you create a List reference to a MutableList , the compiler will produce errors if you try to modify the collection through this reference.
fun main() < //sampleStart val sourceList = mutableListOf(1, 2, 3) val referenceList: List
Invoke functions on other collections
Collections can be created as a result of various operations on other collections. For example, filtering a list creates a new list of elements that match the filter:
Mapping produces a list from a transformation’s results:
For more information about operations on collections in Kotlin, see Collection operations overview.
Kotlin mutablelist from list
List представляет последовательный список элементов. При этом List представляет неизменяемую (immutable) коллекцию, которая в основном только обеспечивает получение элементов по позиции.
Интерфейс List расширяет интерфейс Collection , поэтому перенимает его возможности.
Для создания объекта List применяется метод listOf() :
var numbers = listOf(1, 2, 3, 4, 5) // объект List val people = listOf(«Tom», «Sam», «Kate», «Bob», «Alice») // объект List
Списки поддерживают перебор с помощью цикла for, кроме для списка по умолчанию задача реализация toString, которая выводит все элементы списка в удобочитаемом виде:
val people = listOf("Tom", "Sam", "Kate", "Bob", "Alice") for(person in people) println(person) println(people) // [Tom, Sam, Kate, Bob, Alice]
Методы списков
Кроме унаследованных методов класс List имеет ряд специфичных. Рассмотрим некоторые из них.
Для получения элемента по индексу можно применять метод get(index) , который возвращает элемент по индексу
val people = listOf("Tom", "Sam", "Kate", "Bob", "Alice") val first = people.get(0) val second = people.get(1) println(first) // Tom println(second) // Sam
Вместо метода get для обращения по индексу можно использовать квадратные скобки [] :
val people = listOf("Tom", "Sam", "Kate", "Bob", "Alice") val first = people[0] val second = people[1] println(first) // Tom println(second) // Sam
Однако, если индекс выходит за границы списка, то при использовании метода get() и квадратных скобок генерируется исключение. Чтобы избежать подобной ситуации, можно применять метод getOrNull() , который возвращает null, если индекс находится вне границ списка:
val people = listOf("Tom", "Sam", "Kate", "Bob", "Alice") val first = people.getOrNull(0) val tenth = people.getOrNull(10) println(first) // Tom println(tenth) // null
Либо в качестве альтернативы можно применять метод getOrElse() :
getOrElse(index: Int, defaultValue: (Int) -> T): T
Первый параметр представляет индекс, а второй параметр — функция, которая получает запрошенный индекс и возвращает значение, которое возвращается, если индекс выходит за границы списка:
val people = listOf("Tom", "Sam", "Kate", "Bob", "Alice") val first = people.getOrElse(0) val seventh = people.getOrElse(7) val tenth = people.getOrElse(10) println(first) // Tom println(seventh) // Invalid index 7 println(tenth) // Undefined
Получение части списка
Метод subList() возвращает часть списка и в качестве параметров принимает начальный и конечный индексы извлекаемых элементов:
subList(fromIndex: Int, toIndex: Int): List
Например, получим подсписок с 1 по 4 индексы:
val people = listOf("Tom", "Sam", "Kate", "Bob", "Alice", "Mike") val subPeople = people.subList(1, 4) println(subPeople) // [Sam, Kate, Bob]
Изменяемые списки
Изменяемые списки представлены интерфейсом MutableList . Он расширяет интерфейс List и позволяют добавлять и удалять элементы. Данный интерфейс реализуется классом ArrayList .
Для создания изменяемых списков можно использовать ряд методов:
Создание изменяемых списков:
var numbers : ArrayList = arrayListOf(1, 2, 3, 4, 5) var numbers2: MutableList = mutableListOf(5, 6, 7)
Если необходимо добавлять или удалять элементы, то надо использовать методы MutableList:
- add(index, element) : добавлят элемент по индексу
- add(element) : добавляет элемент
- addAll(collection) : добавляет коллекцию элементов
- remove(element) : удаляет элемент
- removeAt(index) : удаляет элемент по индексу
- clear() : удаляет все элементы коллекции
fun main() < val numbers1 : ArrayList= arrayListOf(1, 2, 3, 4, 5) numbers1.add(4) numbers1.clear() val numbers2: MutableList = mutableListOf(5, 6, 7) numbers2.add(12) numbers2.add(0, 23) numbers2.addAll(0, listOf(-3, -2, -1)) numbers2.removeAt(0) numbers2.remove(5) for (n in numbers2) < println(n) >>