Kotlin learning - set

List related operations

Get elements by index

The feature of List is that it can access specific elements through index, so the easiest way to read an element is to retrieve it by index. Pass the index parameters through the get() function or the short syntax [index]

All common operations of getting elements by index: elementAt(), first(), last(), and getting a single element

If the length of the List is less than the specified index, an exception is thrown, but there are two functions to avoid such exceptions:

  • getOrElse() provides a function to calculate the default value. If there is no index in the collection, it returns the default value
  • getOrNull() returns null as the default value
val numbers = listOf(1,2,3,4)

println(numbers.getOrNull(5))    //null
println(numbers.getOrElse(5, {it}))  //5

Take part of the list

sublist() this function returns the view of the specified element range as a list. Therefore, if the element of the original set changes, it will also change in the previously created sublist, and vice versa

Set related operations

Extension function of common operations: find intersection, union or difference set

Union

To combine two sets into one (Union), use the union() function. a union b can also be used in the form of infix. For ordered sets, the order of the operands is important: in the result set, the left operand comes first

intersection

Find the elements (intersection) that exist in both sets. Use intersect() or call it in the form of infix

Difference set

To find a set element (difference set) that does not exist in another set, use subtract() or call it in the form of infix

val numbers = setOf("one", "two", "three")

println(numbers union setOf("four", "five"))
println(numbers intersect setOf("two","one"))
println(numbers subtract setOf("three", "four"))

List also supports Set operation, but the result of Set operation on list is still Set, and all duplicate elements will be deleted

Map related operations

Take Key and Value

To retrieve the value from the Map, you must provide its Key as the parameter of the get() function, and support the abbreviated [Key] syntax. If the corresponding Key cannot be found, null will be returned. There is also a getValue() function that behaves slightly differently: if the Key is not found in the Map, an exception is thrown. In addition, there are two options to solve the problem of missing keys:

  • getOrElse() works the same way as list: for keys that do not exist, the value is returned by the given lambda expression
  • getOrDefault() returns the specified default value if the key cannot be found

To perform operations on all keys or values of a map, you can retrieve them from the attributes keys and values accordingly. Keys is the set of all values in the map, and values is the set of all values in the map.

filter

You can use the filter() function to filter maps or other collections. When you use the filter() function on a map, Pair passes it a predicate as a parameter, which uses the predicate to filter both the key and the value

There are also two specific functions for filtering Map: press key or press value. Both methods have corresponding functions: filterKeys() and filterValues(); Both will return a new Map with entries that match the given predicate.

filterKeys() only checks element keys; filterValues() checks values only

val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter{ (key, value) -> key.endWith("1") && value > 10}
println(filteredMap)

val filterKeysMap = numbersMap.filterKeys{ it.endsWith("1") }
val filterValuesMap = numbersMap.filterValues{ it < 10 }
println(filteredKeysMap)
println(filteredValuesMap)

Output:
{key11=11}
{key1=1, key11=11}
{key1=1, key2=2, key3=3}

plus and minus operations

Due to the need to access the key of the element, the action of the plus (+) and minus (-) operators on the Map is different from that of other collections. Plus returns a Map containing two operand elements: the Map on the left and the Pair or another Map on the right. When the right operand has a key that already exists in the left Map, the entry will use the value on the right

If the given key already exists in the Map, both put() and putAll() will overwrite the value, so you can use them to update the value of the Map entry

You can also use the quick operator to add new entries to the Map in two ways:

  • pulsAssign(+ =) operator
  • [] operator is the alias of put()
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
val previousValue = numbersMap.put("one", 11)
println("value associated with 'one', before: $previousValue, after: ${numbersMap["one"]}")
println(numbersMap)

numbersMap["three"] = 3
numbersMap += mapOf("four" to 4, "five" to 5)
println(numbersMap)

Output:
value associated with 'one', before: 1, after: 11
{one=11, two=2}
{one=11, two=2, three=3, four=4, five=5}

Delete entry

To delete an entry from a mutable Map, use the remove() function. When you call remove (), you can pass a key or an entire key pair value. If you specify both a key and a value, the element is deleted only if both keys and values match

You can also delete entries from a mutable Map with keys or values. In the Map Keys or remove() is invoked in values and key or value is added to delete entries. Yes When invoking in values, remove() only removes the first entry that the given value matches.

The minusAssign (- =) operator can also be used for mutable maps

val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "threeAgain" to 3)
numbersMap.remove("one")
println(numbersMap)
numbersMap.remove("three", 4)
println(numbersMap)

numbersMap.values.remove(3)
println(numbersMap)
numbersMap -= "two"
println(numbersMap)
numbersMap -= "five"
println(numbersMap)

Output:
{two=2, three=3, threeAgain=3}
{two=2, three=3, threeAgain=3}
{two=2, threeAgain=3}
{threeAgain=3}
{threeAgain=3}

Keywords: Android kotlin

Added by gple on Fri, 28 Jan 2022 04:05:50 +0200