当前位置:网站首页>Kotlin advanced set

Kotlin advanced set

2022-06-25 09:52:00 seevc

This article mainly talks about Kotlin aggregate , It mainly includes List、Set、Array、Map Four types of .

One 、List piece

1.1 Fixed length List

Define the way : Use listOf Define fixed length list aggregate .
Such as :

val list = listOf("Sam", "Jack", "Chork", "Yam")
println(list[2])

Value method :

  • Indexes 、elementAt, These two methods will throw exceptions if they cross the boundary ;
  • getOrElse、elementAtOrElse、getOrNull、elementAtOrNull, These are safe values , No auxiliary processing found ;
    // When obtained in this way , If the index is out of bounds, an exception will be thrown 
    println(list[4])
    println(list.elementAt(1))
    // This method obtains the value of the specified index , If out of bounds, the specified default string will be returned 
    println(list.getOrElse(4){"UnKnown"})
    println(list.getOrElse(2){"UnKnown"})
    // The same as above 
    println(list.elementAtOrElse(4){"UnKnown"})
    // When this method obtains the value of the specified index , If it is out of bounds, it will return null
    println(list.getOrNull(4))
    // The same as above , Internal call getOrNull Method 
    println(list.elementAtOrNull(4))

Element de duplication method :

//*********  De duplication of elements 
list.distinct() // Equivalent to  list.toSet().toList()

To variable length List aggregate

//*********  To a variable set 
val toMutableList = list.toMutableList()

To array mode : The corresponding conversion function will be called according to the data type

// here list Is an object type, so it is necessary to use toTypedArray
val toTypedArray = list.toTypedArray()
// Integers List
listOf(10,20).toIntArray()
1.2 Variable length List

Define the way : Use mutableListOf

val mutableList = mutableListOf("Sam", "Jack", "Chork", "Yam")

Value method : With fixed length List The value is obtained in the same way .
Additive elements : adopt "+="、add function

//************** Additive elements 
mutableList += "Hab"    //mutator function 
mutableList.add("Hab2")
mutableList.add(1,"Hab3")
println(mutableList)

Remove elements : adopt “-=”、remove、removeAt、removeIf( Delete elements that meet the conditions )

//************** Remove elements 
mutableList -= "Sam"
// Remove elements by index 
mutableList.removeAt(0)
mutableList.remove("Hab2")
// Remove eligible data 
mutableList.removeIf{it.contains("k")}
mutableList.removeFirst()
mutableList.removeFirstOrNull()
mutableList.removeLast()
mutableList.removeLastOrNull()
println(mutableList)

To be of variable length List aggregate

//************** Turn immutable List
val toList = mutableList.toList()

turn Set aggregate

//************** turn Set
val toSet = mutableList.toSet()
1.3 List Traverse

Go straight to the example

fun main() {
    val list = listOf("Sam", "Jack", "Chork")

    //***********  Traversal mode 1  ***************
    for (s in list){
         println(s)
    }

    //***********  Traversal mode 2  ***************
    list.forEach {
        println(it)
    }

    //***********  Traversal mode 3   tape index  ***************
    list.forEachIndexed { index, s ->
        println("${index},${s}")
    }

    //***********  Traversal mode 4   tape index  ***************
    list.withIndex().forEach {
        println("${it.index},${it.value}")
    }

    //***********  Traversal mode 5   deconstruction  ***************
    val (first,second,third) = list
    println("$first $second $third")
    // If you don't want to take the value of an element , Can be underlined “_”
    val (origin,_,last) = list
    println("$origin $last")
}

Two 、Set piece

2.1 Of variable length Set aggregate

Define the way :setOf

val set = setOf("Sam", "Jack", "Chork", "Sam")

Value method : And List similar , however set A collection cannot be indexed directly (set[0])

println(set.elementAt(1))
// Safe value taking method 
println(set.elementAtOrElse(1){"UnKnown"})
println(set.elementAtOrNull(1))

To variable length set aggregate

// To variable length Set aggregate 
val toMutableSet = set.toMutableSet()
2.2 Variable length Set aggregate

Define the way :mutableSetOf

val mutableSet = mutableSetOf("Sam", "Jack", "Chork", "Yam")

Additive elements

//*********  Additive elements 
    mutableSet += "Yam"
    mutableSet.add("Hob")
    println(mutableSet)

Remove elements

//*********  Remove elements 
mutableSet -= "Sam"
// Delete eligible elements 
mutableSet.removeIf{it.contains("k")}
println(mutableSet)

To be of variable length Set aggregate

//*********  Turn immutable Set aggregate 
val toSet = mutableSet.toSet()
2.3 Set A collection of traverse

Same as List Traverse

3、 ... and 、Array piece

Kotlin Various types of Array

An array type Create array function
IntArrayintArrayOf
DoubleArraydoubleArrayOf
LongArraylongArrayOf
ShortArrayshortArrayOf
ByteArraybyteArrayOf
FloatArrayfloatArrayOf
BooleanArraybooleanArrayOf
ArrayarrayOf

Example :

fun main() {
    //1.Int Array 
    val intArrayOf = intArrayOf(10, 20, 30)
    //2.Double  Array 
    val doubleArrayOf = doubleArrayOf(2.3, 2.0, 1.5)
    //3.Float  Array 
    val floatArrayOf = floatArrayOf(2.0f, 1.5f)
    //4.Long  Array 
    val longArrayOf = longArrayOf(10L, 20L)
    //5.Short  Array 
    val shortArrayOf = shortArrayOf(10, 20)
    //6.Byte  Array 
    val byteArrayOf = byteArrayOf(1, 2, 3)
    //7.Boolean  Array 
    val booleanArrayOf = booleanArrayOf(true, false)
    //8.Object  Array 
    val arrayOf = arrayOf(User(), User())
}
// Define a class 
private class User

Four 、Map piece

4.1 Of variable length map

Define the way :mapOf

//to Is an extension function defined by infix expression 
val map = mapOf("Jack" to 10, "Sam" to 20, "Luck" to 18)

Value method

//***********  Read Map Value 
println(map["Jack"])
println(map.getValue("Sam"))
// Safe value taking function 
println(map.getOrElse("Sam"){"Unknown"})
println(map.getOrDefault("JJ",0))

4.2 Variable length Map

Define the way :mutableMapOf
map Key value pairs in are Pair type ==> Pair<A, B>

val map = mutableMapOf("Jack" to 10, "Sam" to 20, "Luck" to 18)

towards map Add elements : “+=”、put、getOrPut

//********  Additive elements 
map += "Haha" to 16
map.put("Hob",18)
// Get the specified key Elements , If it does not exist, add the element to map in 
map.getOrPut("Choice"){17}
println(map)

from map Remove elements from , adopt "-="、remove

//********  Remove elements 
map -= "Haha"
map.remove("Jack")
println(map)

map Transfer to other sets

//******** map turn List aggregate 
val toList = map.toList()
println(toList)
4.3 map A collection of traverse

adopt forEach The way , There are two ways

fun main() {
    val map = mapOf("Jack" to 10, "Sam" to 20, "Luck" to 18)

    // Mode one 
    map.forEach {
        println("${it.key},${it.value}")
    }

    // Mode two 
    map.forEach { (t, u) ->
        println("${t} -- ${u}")
    }
}

Welcome to leave a message for us to exchange and learn from each other !


Sample source address kotlin_demo

原网站

版权声明
本文为[seevc]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200547582991.html