当前位置:网站首页>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
边栏推荐
- Vscode attempted to write the procedure to a pipeline that does not exist
- [design completion - opening report] zufeinfo 2018 software engineering major (including FAQ)
- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate
- How to download the school logo, school name and corporate logo on a transparent background without matting
- vscode试图过程写入管道不存在
- 汇付国际为跨境电商赋能:做合规的跨境支付平台!
- How to delete a blank page that cannot be deleted in word
- Title B of the certification cup of the pistar cluster in the Ibagu catalog
- PHP obtains the IP address, and the apache2 server runs without error
- [competition - Rural Revitalization] experience sharing of Zhejiang Rural Revitalization creative competition
猜你喜欢

Encoding format for x86

Question B of the East China Cup: how to establish a population immune barrier against novel coronavirus?

Wechat official account can reply messages normally, but it still prompts that the service provided by the official account has failed. Please try again later

Flutter dialog: cupertinoalertdialog

Pytorch_Geometric(PyG)使用DataLoader报错RuntimeError: Sizes of tensors must match except in dimension 0.

How to "transform" small and micro businesses (I)?

Methodchannel of flutter

8. Intelligent transportation project (1)

Get started quickly with jetpack compose Technology

Cassava tree disease recognition based on vgg16 image classification
随机推荐
Match a mobile number from a large number of mobile numbers
Is it safe to open a stock account on the compass?
2台三菱PLC走BCNetTCP协议,能否实现网口无线通讯?
[buuctf.reverse] 117-120
Pytorch_ Geometric (pyg) uses dataloader to report an error runtimeerror: sizes of tenants must match except in dimension 0
Flutter dialog: cupertinoalertdialog
CyCa children's physical etiquette Yueqing City training results assessment successfully concluded
匯付國際為跨境電商賦能:做合規的跨境支付平臺!
Applet cloud development joint table data query and application in cloud function
Data-driven anomaly detection and early warning of 21 May Day C
[MySQL learning notes 20] MySQL architecture
oracle 函数 触发器
2021mathorcupc topic optimal design of heat dissipation for submarine data center
MySQL source code reading (II) login connection debugging
Methodchannel of flutter
Neat Syntax Design of an ETL Language (Part 2)
Nano data World Cup data interface, CSL data, sports data score, world cup schedule API, real-time data interface of football match
富时A50开户什么地方安全
What functions should smart agriculture applet system design have
Is GF Securities reliable? Is it legal? Is it safe to open a stock account?