List of objects kotlin

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

()`](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) 

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

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

Читайте также:  Array java удаление элемента

Функции копирования коллекций, такие как 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() , которая создаёт ассоциативный список:

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

Источник

Collections overview

The Kotlin Standard Library provides a comprehensive set of tools for managing collections – groups of a variable number of items (possibly zero) that are significant to the problem being solved and are commonly operated on.

Collections are a common concept for most programming languages, so if you’re familiar with, for example, Java or Python collections, you can skip this introduction and proceed to the detailed sections.

A collection usually contains a number of objects (this number may also be zero) of the same type. Objects in a collection are called elements or items. For example, all the students in a department form a collection that can be used to calculate their average age.

The following collection types are relevant for Kotlin:

  • List is an ordered collection with access to elements by indices – integer numbers that reflect their position. Elements can occur more than once in a list. An example of a list is a telephone number: it’s a group of digits, their order is important, and they can repeat.
  • Set is a collection of unique elements. It reflects the mathematical abstraction of set: a group of objects without repetitions. Generally, the order of set elements has no significance. For example, the numbers on lottery tickets form a set: they are unique, and their order is not important.
  • Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. The values can be duplicates. Maps are useful for storing logical connections between objects, for example, an employee’s ID and their position.

Kotlin lets you manipulate collections independently of the exact type of objects stored in them. In other words, you add a String to a list of String s the same way as you would do with Int s or a user-defined class. So, the Kotlin Standard Library offers generic interfaces, classes, and functions for creating, populating, and managing collections of any type.

The collection interfaces and related functions are located in the kotlin.collections package. Let’s get an overview of its contents.

Collection types

The Kotlin Standard Library provides implementations for basic collection types: sets, lists, and maps. A pair of interfaces represent each collection type:

  • A read-only interface that provides operations for accessing collection elements.
  • A mutable interface that extends the corresponding read-only interface with write operations: adding, removing, and updating its elements.

Note that altering a mutable collection doesn’t require it to be a var : write operations modify the same mutable collection object, so the reference doesn’t change. Although, if you try to reassign a val collection, you’ll get a compilation error.

The read-only collection types are covariant. This means that, if a Rectangle class inherits from Shape , you can use a List anywhere the List is required. In other words, the collection types have the same subtyping relationship as the element types. Maps are covariant on the value type, but not on the key type.

In turn, mutable collections aren’t covariant; otherwise, this would lead to runtime failures. If MutableList was a subtype of MutableList , you could insert other Shape inheritors (for example, Circle ) into it, thus violating its Rectangle type argument.

Below is a diagram of the Kotlin collection interfaces:

Collection interfaces hierarchy

Let’s walk through the interfaces and their implementations. To learn about Collection , read the section below. To learn about List , Set , and Map , you can either read the corresponding sections or watch a video by Sebastian Aigner, Kotlin Developer Advocate:

Collection

fun List.getShortWordsTo(shortWords: MutableList, maxLength: Int) < this.filterTo(shortWords) < it.length // throwing away the articles val articles = setOf("a", "A", "an", "An", "the", "The") shortWords -= articles > fun main() < val words = "A long time ago in a galaxy far far away".split(" ") val shortWords = mutableListOf() words.getShortWordsTo(shortWords, 3) println(shortWords) >

List

List elements (including nulls) can duplicate: a list can contain any number of equal objects or occurrences of a single object. Two lists are considered equal if they have the same sizes and structurally equal elements at the same positions.

As you see, in some aspects lists are very similar to arrays. However, there is one important difference: an array’s size is defined upon initialization and is never changed; in turn, a list doesn’t have a predefined size; a list’s size can be changed as a result of write operations: adding, updating, or removing elements.

In Kotlin, the default implementation of MutableList is ArrayList which you can think of as a resizable array.

Set

MutableSet is a Set with write operations from MutableCollection .

The default implementation of MutableSet – LinkedHashSet – preserves the order of elements insertion. Hence, the functions that rely on the order, such as first() or last() , return predictable results on such sets.

An alternative implementation – HashSet – says nothing about the elements order, so calling such functions on it returns unpredictable results. However, HashSet requires less memory to store the same number of elements.

Map

fun main() < //sampleStart val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1) println("All keys: $«) println(«All values: $») if («key2» in numbersMap) println(«Value by key \»key2\»: $») if (1 in numbersMap.values) println(«The value 1 is in the map») if (numbersMap.containsValue(1)) println(«The value 1 is in the map») // same as previous //sampleEnd >

Two maps containing the equal pairs are equal regardless of the pair order.

MutableMap is a Map with map write operations, for example, you can add a new key-value pair or update the value associated with the given key.

The default implementation of MutableMap – LinkedHashMap – preserves the order of elements insertion when iterating the map. In turn, an alternative implementation – HashMap – says nothing about the elements order.

Источник

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