当前位置:网站首页>Use of kotlin arrays, collections, and maps
Use of kotlin arrays, collections, and maps
2022-06-24 13:35:00 【Hua Weiyun】
@[TOC](kotlin Array 、 The collection and Map Use )
Preface
Use pure code Add The way of annotating , You can understand the source code faster
If you like , Please give me a compliment , In the later stage, we will continue to explain in depth
1、List Create and get elements
val list = listOf(" Zhang San "," It's beautiful "," Wang Meili "," Wang Wu ")// Normal value method : Indexes , The inner operator is overloaded [] = get println(list[0]) println(list[1]) println(list[2]) println(list[3]) // println(list[4]) // Subscript out of bounds crash Index 4 out of bounds for length 4// kotlin in , have access to getOrElse and getOrNull , Solve null pointer exception , Subscript out of bounds crash exception // getOrElse When the value is out of bounds , Will go straight back to {" Ah , You crossed the line , I'm out "} The parameters defined in parentheses println(list.getOrElse(0){" You didn't cross the line , I won't come out "}) println(list.getOrElse(4){" Ah , You crossed the line , I'm out "})// getOrNull When the subscript crosses the boundary , Will return a null , We can + Null merge operator , Make it return one character println(list.getOrNull(0)) println(list.getOrNull(4)) println(list.getOrNull(4) ?: " you 're right , That's where it crossed the line , I used the empty merge operator to come out ")2、 variable List aggregate
// Immutable set val list1 = listOf(" Zhang San "," It's beautiful "," Wang Meili "," Wang Wu ") println(list1)// Variable set val list2 = mutableListOf(" Zhang San "," It's beautiful "," Wang Meili "," Wang Wu ") list2.add("tiger") list2.remove(" Wang Wu ") println(list2)// Immutable set to Variable set val list3 = list1.toMutableList() list3.remove(" It's beautiful ") list3.add("tiger") println(list3)// Variable set to Immutable set val list4 = list2.toList()// list4.add There are no methods to add and delete println(list4)3、mutator function
val list2 = mutableListOf(" Zhang San "," It's beautiful "," Wang Meili "," Wang Wu ")// mutator Characteristics of += -= In fact, behind it is Just operator overloading list2 += "tiger" list2 += "tt" list2 -= "tt" println(list2)// removeIf // list2.removeIf{true} // If the value returned is true ,list2 Will automatically traverse the entire variable set , Remove all data one by one list2.removeIf{it.contains("t")} // Filter all elements in the collection , Just include t Data elements , Will be removed println(list2)4、List A collection of traverse Three common ways
val list2 = mutableListOf(" Zhang San ", " It's beautiful ", " Wang Meili ", " Wang Wu ")// 1、 for Loop traversal for (i in list2) { print(" The element is : $i ") } println()// 2、forEach Traverse list2.forEach { print(" The element is : $it") } println()// 3、forEachIndexed Get subscripts and traversal of elements list2.forEachIndexed { index, item -> print(" The subscript is :$index, The element is :$item") }5、 Structural syntax filtering
val list2 = mutableListOf(" Zhang San ", " It's beautiful ", " Wang Meili ", " Wang Wu ")// Set coordination structure syntax val (v1, v2, v3) = list2 println(v1) println(v2) println(v3)// val Is read-only data traversal , have access to var Modify the data from the structure var (v11, v22, v33) = list2 v22 = "tiger" println(v1)// You can also use _ Symbol , To mask the received values you don't need , It's data optimization , Can optimize memory val (_, v222, v333) = list2 println(v222) println(v333)6、set aggregate
set aggregate , Elements cannot be repeated
// set aggregate , Elements cannot be repeated val set = setOf(" Zhang San ", " It's beautiful ", " Wang Meili ", " Wang Wu ", " It's beautiful ")// set Set common value taking method // set[0] stay set in , No, [] This function , take set Set value of set.elementAt(0)// set.elementAt(5) It will collapse across the border // set aggregate and list Like a collection , It provides us with an effective value taking method , It can avoid the occurrence of subscript out of bounds and so on set.elementAtOrElse(0){" Don't cross the border , I won't come out "} set.elementAtOrElse(6){" It's out of bounds , I'm out "} set.elementAtOrNull(0) set.elementAtOrNull(6) ?: " Cross the border , You're back null, Null merge operator , Let me come out and meet you "7、 Variable set aggregate
// list in , There are variable sets ,set Of course, there will be . Including set transformation and so on , reference list Can val set = mutableSetOf(" Zhang San ", " It's beautiful ", " Wang Meili ", " Wang Wu ", " It's beautiful ") set.add("tiger") set.remove(" Wang Wu ") set.removeIf{ it.contains(" king ") } println(set)8、 Set conversion and shortcut functions
val list = mutableListOf(" Zhang San ", " It's beautiful ", " Wang Meili ", " Wang Wu ", " It's beautiful ")// list turn set duplicate removal println(list.toSet())// list turn set duplicate removal , Turn back list println(list.toSet().toList())// Use the quick de duplication function distinct println(list.distinct()) // In fact, it is internally encapsulated , The first List convert to Variable length set To convert list , The operation is the same as above 9、 An array type
stay kotlin In language , Various array types , Although the reference type is used , The back can be compiled into Java Basic types
IntArray intArrayOfDoubleArray doubleArrayOfLongArray longArrayOfShortArray shortArrayOfByteArray byteArrayOfFloatArray floatArrayOfBooleanArray booleanArrayOfArray< object type > arrayOf An array of objects val intArray = intArrayOf(1, 23, 32, 5, 2, 3)// In fact, the array is the same as the set mentioned before , ordinary , I won't repeat intArray[3]// intArray[7] The subscript crossing the line , intArray.elementAtOrElse(3) { -1 } intArray.elementAtOrNull(66) ?: -1// list Set array val set = intArray.toSet() println(set)// Array< An array of objects > val array = arrayOf(File(" File path "), File(" File path "), File(" File path ")) println(array)10、Map The creation of
// stay kotlin in , There are two ways to create map The way , It's actually equivalent val map = mapOf("tiger" to "111", "ss" to "333") val map1 = mapOf(Pair("tiger", "111"), Pair("tiger2", "")) 11、 Read Map Value
val map = mapOf("tiger" to 122, "tiger2" to 333) // Method 1 If it is not found, it will return a null println(map["tiger"]) println(map["tiger333"]) // return null// Method 2 It's the same as an array collection println(map.getOrElse("tiger") {-1}) println(map.getOrElse("tiger222") {-1}) // Can't find it will return -1 // Method 3 getOrDefault println(map.getOrDefault("tiger", -1)) println(map.getOrDefault("tiger4444", -1)) // Can't find it will return -1// Method four getValue println(map.getValue("tiger")) println(map.getValue("tiger666")) // If you can't find it, it will collapse 12、Map The traversal
val map = mapOf(Pair("tiger", 12), Pair("tiger2", 34), Pair("tiger3", 44), Pair("tiger4", 66))// The first one is for (i in map){ println(i) println(i.key) println(i.value) }// The second kind map.forEach{// This it Contains key value println(it) println(it.key) println(it.value) }13、 Variable Map aggregate
val map = mutableMapOf(Pair("tiger", 12), Pair("tiger2", 34), Pair("tiger3", 44), Pair("tiger4", 66))// In fact, it is the same operation as the collection array // Operation of variable sets -= += [] put map += "tiger222" to 322 map -= "tiger222" map["dddd"] = 3000 map.put("ssss", 333) println(map)// getOrPut No incoming tiger555 key Words , He'll put this data , Insert into the whole set println(map.getOrPut("tiger555") { 7777 }) // getOrPut When you need to get key, Found in the collection , Get the corresponding in the set directly value value println(map.getOrPut("tiger555") { 999 })summary
🤩
️
边栏推荐
- Ask a question about SQL view
- 16 safety suggestions from metamask project to solid programmers
- The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine
- 初中级开发如何有效减少自身的工作量?
- Comparator sort functional interface
- 【AI玩家养成记】用AI识别邻居家旺财是什么品种
- Evolution of the message module of the play live series (3)
- Getting started with the go Cobra command line tool
- Android kotlin 大全
- Implement Domain Driven Design - use ABP framework - update operational entities
猜你喜欢

黄金年代入场券之《Web3.0安全手册》

YOLOv6:又快又准的目标检测框架开源啦

爱可可AI前沿推介(6.24)

硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件

CVPR 2022 | 美团技术团队精选论文解读

Interviewer: the MySQL database is slow to query. What are the possible reasons besides the index problem?

一文讲透研发效能!您关心的问题都在

Creation and use of unified links in Huawei applinking

Getting started with the lvgl Library - colors and images

"Interesting" is the competitiveness of the new era
随机推荐
Liux command
kotlin 初始化块
金鱼哥RHCA回忆录:DO447管理项目和开展作业--为ansible剧本创建一个项目
Sinomeni vine was selected as the "typical solution for digital technology integration and innovative application in 2021" of the network security center of the Ministry of industry and information te
敏捷之道 | 敏捷开发真的过时了么?
openGauss内核:简单查询的执行
问个sql view的问题
Implement Domain Driven Design - use ABP framework - create entities
Memory introduction
#yyds干货盘点# 解决剑指offer:调整数组顺序使奇数位于偶数前面(二)
Gateway processing flow of zuul source code analysis
Source code analysis handler interview classic
[one picture series] one picture to understand Tencent Qianfan apaas
快速了解常用的消息摘要算法,再也不用担心面试官的刨根问底
Vim 常用快捷键
Yolov6: the fast and accurate target detection framework is open source
kotlin 匿名函数 与 Lambda
Talk about GC of JVM
‘高并发&高性能&高可用服务程序’编写及运维指南
Cmput 379 explanation