当前位置:网站首页>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
- JS tool function, self encapsulating a throttling function
- Processing picture class library
- [buuctf.reverse] 117-120
- [2020 cloud development + source code] 30 minutes to create and launch wechat applet practical project | zero cost | cloud database | cloud function
- TLAB mechanism of JVM object memory allocation and TLAB process in G1
- How to make a self-made installer and package the program to generate an installer
- 使用EVO
- oracle 函数 触发器
- [smart agriculture program] smart agriculture small program project is currently popular.
猜你喜欢

Analysis on the thinking of 2022 meisai C question

Prediction of pumpkin price based on BP neural network

Question B of the East China Cup: how to establish a population immune barrier against novel coronavirus?
![[IOU] intersection over union](/img/17/a3e2144dfbd9248034cae285ee85bd.jpg)
[IOU] intersection over union

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

Download the arm64 package of Debian on X86 computer

manhattan_slam环境配置

x86的编码格式
![[MySQL learning notes 21] storage engine](/img/3a/a3cd573281efc689cafdb7d7562ce0.png)
[MySQL learning notes 21] storage engine

SQL advanced
随机推荐
Is it safe to open a stock account through the account opening QR code of the account manager?
Is it safe to open an account on the compass?
Mengyou Technology: six elements of tiktok's home page decoration, how to break ten thousand dollars in three days
[MySQL learning notes 22] index
Question B of the East China Cup: how to establish a population immune barrier against novel coronavirus?
处理图片类库
Vscode attempted to write the procedure to a pipeline that does not exist
Wallys/MULTI-FUNCTION IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL
Is GF Securities reliable? Is it legal? Is it safe to open a stock account?
Get started quickly with jetpack compose Technology
Learning notes of rxjs takeuntil operator
链表 删除链表中的节点
oracle 函数 触发器
Neat Syntax Design of an ETL Language (Part 2)
What functions should smart agriculture applet system design have
[buuctf.reverse] 121-125
8. Intelligent transportation project (1)
SparseArray details
Shuttle JSON, list, map inter transfer
How to download the school logo, school name and corporate logo on a transparent background without matting