当前位置:网站首页>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
边栏推荐
- Match a mobile number from a large number of mobile numbers
- Jetpack compose layout (III) - custom layout
- JS tool function, self encapsulating a throttling function
- MySQL创建给出语句
- Solution to the problem of repeated startup of esp8266
- What are the PMP scores?
- 瑞萨RA系列-开发环境搭建
- C语言刷题随记 —— 猴子吃桃
- Processing picture class library
- Is GF Securities reliable? Is it legal? Is it safe to open a stock account?
猜你喜欢

Mengyou Technology: tiktok live broadcast with goods elements hot topics retention skills shaping image highlight selling points

2021mathorcupc topic optimal design of heat dissipation for submarine data center

Vscode attempted to write the procedure to a pipeline that does not exist

字符串 最长公共前缀

puzzle(019.2)六边锁

链表 删除链表中的节点

Jetpack compose layout (III) - custom layout

2台三菱PLC走BCNetTCP协议,能否实现网口无线通讯?

【mysql学习笔记21】存储引擎

Question B of the East China Cup: how to establish a population immune barrier against novel coronavirus?
随机推荐
Wearable devices may reveal personal privacy
Mengyou Technology: tiktok live broadcast with goods elements hot topics retention skills shaping image highlight selling points
8. Intelligent transportation project (1)
Learning notes of rxjs takeuntil operator
How to download the school logo, school name and corporate logo on a transparent background without matting
pmp考试题型需要注意哪些?
【mysql学习笔记21】存储引擎
TLAB mechanism of JVM object memory allocation and TLAB process in G1
Armbian version name comparison
链表 删除链表中的节点
oracle 函数 触发器
瑞萨RA系列-开发环境搭建
8、智慧交通项目(1)
manhattan_ Slam environment configuration
Mysql 源码阅读(二)登录连接调试
Neo4jdesktop (neo4j desktop version) configures auto start (boot auto start)
Prediction of pumpkin price based on BP neural network
Use Navicat to compare data differences and structure differences of multi environment databases, and automatic DML and DDL scripts
Question B of the East China Cup: how to establish a population immune barrier against novel coronavirus?
Rxjs TakeUntil 操作符的学习笔记