Kotlin collections come in two types: read-only and mutable
Create and get
Fun main() {val list = listOf<String>(" Jason ", "Jack ", "dog") print(list[3]) Index value Second argument: Print (list.getorNull (3){"unKnown"}) print(list.getorNull (3)? :"unKnown") }Copy the code
Create a mutableList
Val mutableListOf = mutableListOf(" Jason ", "Jack ", "dog") mutableListOf. Add ("cat") mutableListOf. Remove (" Jack ")Copy the code
The list in Kotlin that supports content modification is called a mutable list, and you can use the mutableListOf function. List also supports dynamic conversion between read-only and mutable lists using toList and toMutableList
Val toList = mutablelistof.tolist ()Copy the code
Mutator functions:
Functions that modify mutable lists have a common name: the mutator function
// Functions that modify mutable lists have a common name: The mutator function mutableListOf += "Jimmy"// adds Jimmy mutableListOf -= "Jimmy"// removes Jimmy // If the element in the list contains dog mutableListOf.removeIf { it.contains("dog") }Copy the code
Traversal (three ways)
ForEach {print(it)} forEach {print(it)} //forEachIndexed indexed index list2.forEachIndexed { index, item -> print("$index, $item") }Copy the code
deconstruction
Val list2 = listOf("j", "k", "l"); String) = list2 // Use _ to skip the assignment of this element val (origin1: String, _: String, proxy1: String) = list2 // Print the assigned StringCopy the code
The Set collection
Create and get
Set = setOf("j", "k", "c", "y")Copy the code
Variable set
val mutableSet = mutableSetOf("j", "k", "c", Add ("m") mutableset. remove("m") mutableSet += "n" mutableSet -= "n"Copy the code
Set to list conversion and list de-duplication
Val toSet = listOf("a", "b", "c", ToList1 = toset.tolist () // go back toList // print(toList1) //distinct quick function val distinct = listOf("a", "b", "c", "a").distinct()Copy the code
An array type
Val toIntArray = listOf(10, 20, 30) Val arrayOf = arrayOf("1", "2", "3")Copy the code
Map creation and traversal
Val mapOf = mapOf("jack" to 20, "Wang" to 30, "liu" to 40) Pair("b", Val I = mapOf["jack"] mapOf. GetValue ("jack") mapOf. GetOrElse (" Jack ") {" unknown "} val I = mapOf[" Jack "] mapOf MapOf. GetOrDefault (" Jack ", 0) // The default is 0 // traverses the map mapOf. u -> print("$t,$u") } mapOf.forEach { print(it.key + it.value) }Copy the code
Variable map
Val mutableMapOf = mutableMapOf(" Jack "to 20," Wang "to 30, "Liu" to 40) mutableMapOf += "Jimmy" to 50 mutableMapOf[" Jimmy "] = 30 // Add (jack,18) mutableMapOf. {18}Copy the code