当前位置:网站首页>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
🤩
️
边栏推荐
- How to create a new empty branch in the web development process of easyrtc?
- 硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件
- kotlin 初始化块
- How long will it take to open a mobile account? Is online account opening safe?
- 工业物联网(IIoT)的八个主要趋势
- Can inspection results be entered after the completion of inspection lot UD with long-term inspection characteristics in SAP QM?
- Preparation and operation & Maintenance Guide for 'high concurrency & high performance & high availability service program'
- kotlin 关键字 扩展函数
- 系统测试主要步骤
- Detailed explanation of abstractqueuedsynchronizer, the cornerstone of thread synchronization
猜你喜欢

One article explains R & D efficiency! Your concerns are

Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer

脚本之美│VBS 入门交互实战
![[data mining] final review (sample questions + a few knowledge points)](/img/90/a7b1cc2063784fb53bb89b29ede5de.png)
[data mining] final review (sample questions + a few knowledge points)

Parti,谷歌的自回归文生图模型

Developer survey: rust/postgresql is the most popular, and PHP salary is low

Teach you how to use airtestide to connect your mobile phone wirelessly!

Detailed explanation of abstractqueuedsynchronizer, the cornerstone of thread synchronization

3. caller service call - dapr

Comparator sort functional interface
随机推荐
kotlin 关键字 扩展函数
Gateway processing flow of zuul source code analysis
How stupid of me to hire a bunch of programmers who can only "Google"!
华为AppLinking中统一链接的创建和使用
Integrate API interface parameter Dictionary of accounts of multiple local distribution companies - Express 100
CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan
Comparator sort functional interface
8 lines of code to teach you how to build an intelligent robot platform
CPU process priority
#yyds干货盘点# 解决剑指offer:调整数组顺序使奇数位于偶数前面(二)
Hands on data analysis unit 3 model building and evaluation
Prometheus PushGateway 碎碎念
Introduction to reptile to give up 01: Hello, reptile!
我从根上解决了微信占用手机内存问题
Summary of the process of restoring damaged data in MySQL database
Cohere、OpenAI、AI21联合发布部署模型的最佳实践准则
Who is the fish and who is the bait? Summary of honeypot recognition methods from the perspective of red team
"I, an idiot, have recruited a bunch of programmers who can only" Google "
青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
MySQL interview questions