Kotlin put to map

HashMap

Hash table based implementation of the MutableMap interface.

This implementation makes no guarantees regarding the order of enumeration of keys, values and entries collections.

Constructors

Constructs an empty HashMap instance.

Constructs an instance of HashMap filled with the contents of the specified original map.

Properties

entries

Returns a MutableSet of all key/value pairs in this map.

keys

Returns a MutableSet of all keys in this map.

size

Returns the number of key/value pairs in the map.

values

Returns a MutableCollection of all values in this map. Note that this collection may contain duplicate values.

Functions

clear

Removes all elements from this map.

containsKey

Returns true if the map contains the specified key.

containsValue

Returns true if the map maps one or more keys to the specified value.

equals

Indicates whether some other object is «equal to» this one. Implementations must fulfil the following requirements:

get

Returns the value corresponding to the given key, or null if such a key is not present in the map.

hashCode

Returns a hash code value for the object. The general contract of hashCode is:

isEmpty

Returns true if the map is empty (contains no elements), false otherwise.

put

Associates the specified value with the specified key in the map.

putAll

Updates this map with key/value pairs from the specified map from.

remove

Removes the specified key and its corresponding value from this map.

toString

Returns a string representation of the object.

Inherited Functions

isEmpty

Extension Functions

all

Returns true if all entries match the given predicate.

any

Returns true if map has at least one entry.

Returns true if at least one entry matches the given predicate.

asIterable

Creates an Iterable instance that wraps the original map returning its entries when being iterated.

asSequence

Creates a Sequence instance that wraps the original map returning its entries when being iterated.

contains

Checks if the map contains the given key.

containsKey

Returns true if the map contains the specified key.

containsValue

Returns true if the map maps one or more keys to the specified value.

count

Returns the number of entries in this map.

Returns the number of entries matching the given predicate.

filter

Returns a new map containing all key-value pairs matching the given predicate.

filterKeys

Returns a map containing all key-value pairs with keys matching the given predicate.

filterNot

Returns a new map containing all key-value pairs not matching the given predicate.

filterNotTo

Appends all entries not matching the given predicate into the given destination.

filterTo

Appends all entries matching the given predicate into the mutable map given as destination parameter.

filterValues

Returns a map containing all key-value pairs with values matching the given predicate.

firstNotNullOf

Returns the first non-null value produced by transform function being applied to entries of this map in iteration order, or throws NoSuchElementException if no non-null value was produced.

firstNotNullOfOrNull

Returns the first non-null value produced by transform function being applied to entries of this map in iteration order, or null if no non-null value was produced.

Читайте также:  Inputting files in python

flatMap

Returns a single list of all elements yielded from results of transform function being invoked on each entry of original map.

flatMapTo

Appends all elements yielded from results of transform function being invoked on each entry of original map, to the given destination.

forEach

Performs the given action on each entry.

get

Returns the value corresponding to the given key, or null if such a key is not present in the map.

getOrElse

Returns the value for the given key if the value is present and not null . Otherwise, returns the result of the defaultValue function.

getOrPut

Returns the value for the given key if the value is present and not null . Otherwise, calls the defaultValue function, puts its result into the map under the given key and returns the call result.

getValue

Returns the value for the given key or throws an exception if there is no such key in the map.

ifEmpty

Returns this map if it’s not empty or the result of calling defaultValue function if the map is empty.

isNotEmpty

Returns true if this map is not empty.

isNullOrEmpty

Returns true if this nullable map is either null or empty.

map

Returns a list containing the results of applying the given transform function to each entry in the original map.

mapKeys

Returns a new Map with entries having the keys obtained by applying the transform function to each entry in this Map and the values of this map.

mapKeysTo

Populates the given destination map with entries having the keys obtained by applying the transform function to each entry in this Map and the values of this map.

mapNotNull

Returns a list containing only the non-null results of applying the given transform function to each entry in the original map.

mapNotNullTo

Applies the given transform function to each entry in the original map and appends only the non-null results to the given destination.

mapTo

Applies the given transform function to each entry of the original map and appends the results to the given destination.

mapValues

Returns a new map with entries having the keys of this map and the values obtained by applying the transform function to each entry in this Map.

mapValuesTo

Populates the given destination map with entries having the keys of this map and the values obtained by applying the transform function to each entry in this Map.

maxByOrNull

Returns the first entry yielding the largest value of the given function or null if there are no entries.

maxOf

Returns the largest value among all values produced by selector function applied to each entry in the map.

maxOfOrNull

Returns the largest value among all values produced by selector function applied to each entry in the map or null if there are no entries.

maxOfWith

Returns the largest value according to the provided comparator among all values produced by selector function applied to each entry in the map.

maxOfWithOrNull

Returns the largest value according to the provided comparator among all values produced by selector function applied to each entry in the map or null if there are no entries.

maxWith

Returns the first entry having the largest value according to the provided comparator.

maxWithOrNull

Returns the first entry having the largest value according to the provided comparator or null if there are no entries.

Читайте также:  Python как пропустить input

minByOrNull

Returns the first entry yielding the smallest value of the given function or null if there are no entries.

minOf

Returns the smallest value among all values produced by selector function applied to each entry in the map.

minOfOrNull

Returns the smallest value among all values produced by selector function applied to each entry in the map or null if there are no entries.

minOfWith

Returns the smallest value according to the provided comparator among all values produced by selector function applied to each entry in the map.

minOfWithOrNull

Returns the smallest value according to the provided comparator among all values produced by selector function applied to each entry in the map or null if there are no entries.

minus

Returns a map containing all entries of the original map except the entry with the given key.

Returns a map containing all entries of the original map except those entries the keys of which are contained in the given keys collection.

Returns a map containing all entries of the original map except those entries the keys of which are contained in the given keys array.

Returns a map containing all entries of the original map except those entries the keys of which are contained in the given keys sequence.

Источник

Map: специфичные операции

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

Получение ключей и значений

Для того чтобы получить значение из Map , вы должны передать его ключ в качестве аргумента функции get() . Также поддерживается сокращённый синтаксис — Kotlin put to map . Если такой ключ не найден, то вернётся null . Помимо этого существует функция getValue() , которая в случае отсутствия ключа бросит исключение. Также есть еще две функции для решения проблемы отсутствия ключа:

  • getOrElse() — работает так же, как и для списков: если ключ не найден, то вернётся результат выполнения лямбды.
  • getOrDefault() — если ключ не найден, то вернёт заданное значение по умолчанию.

Если для выполнения операций вам требуются все ключи или все значения из Map , то воспользуйтесь свойствами keys и values . keys — это набор ( Set ) всех ключей, а values — коллекция всех значений.

Фильтрация

Вы можете фильтровать ассоциативный список с помощью функции filter() как и другие коллекции. Для этого передайте filter() предикат с Pair в качестве аргумента, что позволит использовать и ключ, и значение в предикате.

fun main() < val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11) val filteredMap = numbersMap.filter < (key, value) ->key.endsWith("1") && value > 10> println(filteredMap) // > 

Помимо этого существует две функции фильтрации, специфичные именно для ассоциативного списка: filterKeys() для фильтра по ключам и filterValues() для фильтра по значениям. Обе возвращают новый ассоциативный список, в котором все записи соответствуют заданному предикату. Предикат функции filterKeys() проверяет только ключи элементов, а предикат функции filterValues() проверяет только значения.

fun main() < val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11) val filteredKeysMap = numbersMap.filterKeys < it.endsWith("1") >val filteredValuesMap = numbersMap.filterValues < it < 10 >println(filteredKeysMap) // println(filteredValuesMap) // > 

Операторы plus и minus

Из-за наличия доступа к элементам по их ключам операторы plus ( + ) и minus ( — ) работают с ассоциативными списками иначе, чем с другими коллекциями. Оператор plus возвращает Map , которая содержит в себе элементы обоих операндов: первым операндом должен быть Map , а вторым может быть Pair или другая Map . Если второй операнд содержит в себе записи с ключами, которые есть в первом операнде, то в результирующую Map попадут записи из второго операнда.

fun main() < val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3) println(numbersMap + Pair("four", 4)) // println(numbersMap + Pair("one", 10)) // println(numbersMap + mapOf("five" to 5, "one" to 11)) // > 

Оператор minus создаёт Map на основе первого операнда, исключая те записи, ключи которых есть во втором операнде. Таким образом, второй операнд может быть либо одним ключом, либо коллекцией ключей: списком, множеством и так далее.

fun main() < val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3) println(numbersMap - "one") // println(numbersMap - listOf("two", "four")) // > 

Подробнее об использовании операторов plusAssign ( += ) и minusAssign ( -= ) с изменяемыми ассоциативными списками см. ниже Операции записи.

Читайте также:  PHP Database Connection Test

Операции записи

Изменяемые ассоциативные списки предлагают специфичные для них операции записи. Такие операции позволяют изменять содержимое ассоциативного списка, используя доступ к значениям по ключу.

Все операции записи придерживаются следующих правил:

  • Значения можно обновлять. В свою очередь, ключи никогда не меняются: как только вы добавили запись, её ключ остаётся неизменным.
  • Для каждого ключа всегда есть одно значение, связанное с ним. Вы можете добавлять и удалять записи целиком.

Ниже описаны функции для операций записи из стандартной библиотеки, доступные для использования с изменяемыми ассоциативными списками.

Добавление и обновление записи

Для добавления в изменяемый ассоциативный список новой пары «ключ-значение» используйте функцию put() . Когда новая запись помещается в LinkedHashMap (реализация Map по умолчанию), она добавляется в неё таким образом, что при итерации Map она отображается последней. В отсортированных ассоциативных списках положение новых элементов определяется порядком их ключей.

Для добавления нескольких записей за раз, используйте функцию putAll() . В качестве аргумента она принимает Map или группу из Pair : Iterable , Sequence , или Array .

И put() , и putAll() перезаписывают значения, если указанные ключи уже существуют в Map . Поэтому вы можете использовать их, чтобы обновить значения записей.

fun main() < val numbersMap = mutableMapOf("one" to 1, "two" to 2) val previousValue = numbersMap.put("one", 11) println("value associated with 'one', before: $previousValue, after: $") // 11 println(numbersMap) // > 

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

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

Удаление записей

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

fun main() < val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3) numbersMap.remove("one") println(numbersMap) // numbersMap.remove("three", 4) // ничего не удаляет println(numbersMap) // > 

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

fun main() < val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "threeAgain" to 3) numbersMap.keys.remove("one") println(numbersMap) // numbersMap.values.remove(3) println(numbersMap) // > 

Оператор minusAssign ( -= ) для изменяемых Map тоже доступен.

fun main() < val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3) numbersMap -= "two" println(numbersMap) // numbersMap -= "five" // ничего не удаляет println(numbersMap) // > 

Источник

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