当前位置:网站首页>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

🤩
Originality is not easy. , I also hope you guys can support \textcolor{blue}{ Originality is not easy. , I also hope you guys can support }

give the thumbs-up , Your recognition is the driving force of my creation ! \textcolor{green}{ give the thumbs-up , Your recognition is the driving force of my creation !}

Collection , Your favor is the direction of my efforts ! \textcolor{green}{ Collection , Your favor is the direction of my efforts !}

Comment on , Your opinion is the wealth of my progress ! \textcolor{green}{ Comment on , Your opinion is the wealth of my progress !}

原网站

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241234579082.html