当前位置:网站首页>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 |
---|---|
IntArray | intArrayOf |
DoubleArray | doubleArrayOf |
LongArray | longArrayOf |
ShortArray | shortArrayOf |
ByteArray | byteArrayOf |
FloatArray | floatArrayOf |
BooleanArray | booleanArrayOf |
Array | arrayOf |
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
边栏推荐
- Is it safe to open an account online? Who can I ask?
- Study on correlation of pumpkin price and design of price prediction model based on BP neural network
- How to download the school logo, school name and corporate logo on a transparent background without matting
- Learning notes of rxjs takeuntil operator
- Vscode attempted to write the procedure to a pipeline that does not exist
- MySQL创建给出语句
- vscode试图过程写入管道不存在
- Arduino bootloader burning summary
- [zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)
- Neo4jdesktop (neo4j desktop version) configures auto start (boot auto start)
猜你喜欢
Study on correlation of pumpkin price and design of price prediction model based on BP neural network
The gradle configuration supports the upgrade of 64 bit architecture of Xiaomi, oppo, vivo and other app stores
vscode试图过程写入管道不存在
Unique Wulin, architecture selection manual (including PDF)
[zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)
Pytorch_ Geometric (pyg) uses dataloader to report an error runtimeerror: sizes of tenants must match except in dimension 0
Reasons for Meiye to choose membership system
CyCa children's physical etiquette Yueqing City training results assessment successfully concluded
独步武林,架构选型手册(包含 PDF)
可穿戴设备或将会泄露个人隐私
随机推荐
Creo makes a mobius belt in the simplest way
Rxjs TakeUntil 操作符的学习笔记
纳米数据世界杯数据接口,中超数据,体育数据比分,世界杯赛程api,足球比赛实时数据接口
Wallys/MULTI-FUNCTION IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL
Title B of the certification cup of the pistar cluster in the Ibagu catalog
How to "transform" small and micro businesses (II)?
Why should the terminal retail industry choose the member management system
SparseArray details
Online notes on Mathematics for postgraduate entrance examination (9): a series of courses on probability theory and mathematical statistics
处理图片类库
Unique Wulin, architecture selection manual (including PDF)
Where is safe for FTSE A50 to open an account
[zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)
51 SCM time stamp correlation function
CyCa 2022 children's physical etiquette primary teacher class Shenzhen headquarters station successfully concluded
Arduino bootloader burning summary
Data-driven anomaly detection and early warning of 21 May Day C
[buuctf.reverse] 121-125
Mengyou Technology: six elements of tiktok's home page decoration, how to break ten thousand dollars in three days
Creating a binary tree (binary linked list) from a generalized table