“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”


An overview of the

Kotlin doesn’t actually implement any collection classes. Instead, it uses type aliases to specify an alias under the Kotlin package for the original Java collection classes. Kotlin’s Collection is also derived from the Collection and Map interfaces.

The sets in Kotlin are classified into two categories: Mutable and immutable. Only mutable collections can add, delete, and modify elements; immutable collections can only read elements.

Kotlin collection inheritance tree structure

A simple inheritance tree for the Collection architecture is shown below:

The inheritance tree of Map set system is as follows:

The use of the Set

create

We can use the following functions to create sets:

SetOf() // Returns an immutable Set of elements in the order they were added to. LinkedSetOf () // Returns a variable set of hashsets, with no guarantee of element order. SortedSetOf () // Returns a mutable set of TreeSet elements arranged in order of additionCopy the code

Sets created by setOf(), mutableSetOf(), and linkedSetOf() all maintain the order of elements, while sets created by hashSetOf() are unordered.

Processing (operation)

There are some generic handlers for the last section alone. Here are the Set specific handlers:

Set1 intersect set2 // take the intersection set1 union set2 // take the union set1 + set2 // add the set, which is equivalent to take the union set1 - set2 // subtract the set from set1, subtract the elements that are common to set1 and set2Copy the code

Example:

fun main() { val set1 = setOf("Kotlin", "Java", "Go", "Python") val set2 = setOf("Kotlin", "C", "NodeJs", "Java") println(set1 intersect set2) println(set1 union set2) println(set1 + set2) println(set1-set2)} // Run result [Kotlin, Java] [Kotlin, Java, Go, Python, C, NodeJs] [Kotlin, Java, Go, Python, C, NodeJs] [Go, Python]Copy the code

traverse

  • For-in loop traversal
  • ForEach () traverses
  • Use index traversal

Example:

fun main() { val set1 = hashSetOf("Kotlin", "Java", "Go", "Python") / / - for - in traversal for characters in (e) {print (" $e ")} println (" \ n = = = = = = = = = = = = = = = = = = ") / / - forEach () traversal -- characters. ForEach ({print (" $it ")}) println (" \ n = = = = = = = = = = = = = = = = = = ") / / - using the index traversal - for (I in characters. The indices) { Print (" ${characters. ElementAt (I)} ")}} / / run results Go Java Kotlin Python = = = = = = = = = = = = = = = = = = Go Java Kotlin Python ================== Go Java Kotlin PythonCopy the code

Add and delete (MutableSet)

Add (element: E) add(element: E) add(element: E) RemoveAll (elements: Collection<E>) Collection<E>)Copy the code

Both Set and MutableSet contain an iterator() method. An immutable Set returns an iterator that has only hasNext() and next() methods. A mutable Set returns a MutableIterator, and in addition to hasNext() and next(), there is a remove() method that can be used to remove elements during traversal.

Example:

fun main() { val set = hashSetOf("Kotlin", "Java", "Go", "Python") val itr = set.iterator() while (itr.hasNext()) { val e = itr.next() if (e.length < 3) { itr.remove() } } Println (set)}Copy the code

List the use of

It’s a little bit easier, I’ll just write it like this:

ListOfNotNull () // Create a mutableList mutableListOf() // create a mutableList mutableListOf() Create mutable ArrayList arrayListOf()Copy the code
[] get(index: Int) // Return the index of the element that does not exist. Return -1 indexOf(element: E) // Return the index lastIndexOf(element: E) // Return subList(start: Int, end: Int)Copy the code

The use of the Map

Map collections are used to store key-value pairs.

HashMapOf (); hashMapOf(); linkedhashMapof (); // Create a mutable TreeMap set sortedMapOf()Copy the code

Example:

Funmain () {val map = mapOf("Java" to 4, "Kotlin" to 5, "G0" to 2) val map2 = mutableMapOf("Java" to 4, "Kotlin" to 5, "G0" to 2) map2["Python"] = 6 println(map2) }Copy the code

traverse

  • Use the Entries property
  • The map key is iterated and the value is obtained by the key
  • Use deconstruction
  • Use forEach + Lambda expressions

Example:

Fun main() {var map = mapOf("Kotlin" to 32, "Java" to 55, "Python" to 41) Use the entries attribute for (en in map.entries) {println("key=${en.key}, value=${en.value}")} Value for (key in map.keys) {println("key=${key}, value=${map[key]}")} For ((key, value) in map) {println("key=$key, value=$value")} Println ("key=${it.key}, value=${it.value}")}}Copy the code

Multiplication and deletion are Mutable

Remove (key: K) // Add key pairs. If the key already exists, the value will be overwritten. Put (key: K, value: V) // Add putAll(from: Map<out K, V>)Copy the code

In addition, MutableMap provides a set(key, value) method for placing key-value pairs, which can be placed by [] as an operator.

Common array and collection handlers

  • all(predicate: (T) -> Boolean)

Return true if all elements satisfy this expression, false otherwise.

  • any(predicate: (T) -> Boolean)

Returns true if any element satisfies this expression, false if none.

  • cantains(element: T)

Whether the element Element is included

  • first | last(predicate: (T) -> Boolean)

Gets the first or last element that satisfies the condition

  • indexOfFirst | indexOfLast(predicate: (T) -> Boolean)

Gets the index of the first or last element that meets the condition

  • max | min()

Find the maximum or minimum value according to the natural ordering rules that require elements to implement the Comparable interface

There are many more, and I will not list them here.