Short step without thousands of miles, not small streams into rivers and seas

Let’s take a look at the for loop in Kotlin

 fun  testList(){
        var StringVal = "12_12_13_15_a_b_c_d_yu_er"
        var ssArray = StringVal.split("_")
        var ss01 = ssArray[0]
        var ss02 = ssArray[1]
        var size =  ssArray.size
        println("ss01:   $ss01")
        println("ss02:   $ss02")
        println("size:$size")
        val items = listOf("apple"."banana"."kiwi") / / iterationforcyclefor (item in ssArray){
            println("item:  $item")}for (item in ssArray)  println("item:  $item"// The body of the loop can be a block of code:for (item : String in ssArray ){
            println("item:  $item"} // iterate through the index,forYou can loop over any object that provides an iterator. // If you want to traverse an array or a list by index // note this"Go over the interval"It compiles to an optimized implementation without creating additional objects.for (i in ssArray.indices) {
            print(ssArray[I])} //"Go over the interval"It compiles to an optimized implementation without creating additional objects. Or you can use the library withIndex: fun forbetween(index :Int,value: Objects){withIndex: fun forbetween(index :Int,value: Objects){for ((index,value) in ssArray.withIndex()){
                println("the element at $index is $value")}}}Copy the code

Kotlin and the collection utility classes in Java

Collections and their utility classes in Java Collections in Java and their utility classes in Kotlin
List MutableList
Set MutableSet
Map MutableMap
Collection MutableCollection
List MutableList
Set MutableSet
Map MutableMap
Collection MutableCollection
可迭代 MutableIterable
, Kotlin made more concise and effective encapsulation for sets
  • Iterable: parent class. All we can go through is a series of implementations of this interface.

  • MutableIterable: An Iterables that can iterate and delete at the same time.

  • Collection: This class is a generic Collection. We can return the size of the collection, whether it is empty, and whether it contains one or more items via function access. All methods of this collection provide queries because connections is not modifiable.

  • MutableCollection: A Collection that supports adding and removing items. It provides additional functions such as add, remove, clear, and so on.

  • List: Probably the most popular collection type. It’s a conventionally ordered set. Because of its order, we can access it through position using the get function.

  • MutableList: a List of items that can be added or deleted.

  • Set: an unordered collection that does not support repeating items.

  • MutableSet: A Set that supports adding and removing items.

  • Map: a collection of key-value pairs. Keys are unique in a map. That is, no two key-value pairs with the same key can exist in a map.

  • MutableMap: A map that supports adding and removing items.

For example, lists manage collections of objects in a linear fashion, allowing you to quickly add and remove elements anywhere. The List interface inherits the Collection interface, which can hold duplicate objects.

The implementation of the interface

Kotlin could write:

In Java, you can’t write:

Collection creation

Val list2 = mutableListOf<Int>() val list1 = listOf<Int>() Val list3 = arrayListOf<Int>() // Returns a Java ArrayListsetList = setOf<Int>() // returns kotlin'ssetSet, an unordered set that does not support duplicate itemssetMutableList = mutableSetOf<Int>() // Returns kotlin'ssetThe collection MutableSet reads and writes varhashSet = hashSetOf<Int>() // Returns JavasetA collection ofhashVar map = mapOf<String, Int>() var map = mapOf<String, Int>(hashMapOf<String, Int>() {list2.add(1) var first: Int = list2.first() list3.add(1) var first2 : Int = list3.first()Copy the code

Set the set:

Some common usages

The elements in a set are not duplicated and are out of order. To create a set, use setOf(), mutableSetOf() :

val set= setOf<String>(
        "Zaun"."Piltwolf"
)
val mutableSet= mutableSetOf<String>(
        "Arista"."Sewell"
)
Copy the code

Map: A Map is a collection of keys and values. Each element contains keys and values. Kotlin maps, like lists, are classified into read-only and mutable maps.

Call mapOf() to create a Map, mutableMapOf() :

val map= mapOf<Int,String>(
        1 to "Izelere", 2 to "Laketon", 3 to "Gulagas.", 4 to "Tydamir"
)
val hashMap= hashMapOf<Int,String>(
        1 to "Izelere", 2 to "Laketon", 3 to "Gulagas.", 4 to "Tydamir"
)
Copy the code

The difference between map and hashMap is not mentioned here, the basis of Java

Val count=map.size val keys=map.keysprintValues =map.values (::) // return the set of keys in the map.printVal entry=map.entries // Return set of key/value pairs entry. ForEach {println("key: ${it.key} , value: ${it.value}"} // Output key:1, value: Ezarel key:2... Val isEmpty=map.isEmpty() Boolean isContainsKey=map.containsKey(3) // Check whether the set contains a key val isContainsValue=map.containsValue("Laketon"Get (2) returns the element value of the specified key, or null if notCopy the code

A map is read-only like a list. Mutable maps need to use mutableMaps:

Var mutableMapOf= mutableMapOf<Int,String>() putAll(map)"Lacos"Remove (2) // Remove the element mutableMapOf. Clear () // clear the setCopy the code

In many cases, the names of functions and methods are the same as those of lists.

Set operator

Val list = listOf(1, 2, 3, 4, 5, 6) list.any {// As long as any element in the collection satisfies the condition (such that the lambda expression returns)trueThe any function returnstrueIt >= 0} list.all {// All elements in the collection satisfy the condition (such that the lambda expression returns)true), the all function returnstrueIt >= 0} list.none {// If there are no elements in the collection that satisfy the condition (make lambda expression return)true), none returnstrueIt < 0} list.count {//count returns the total number of elements in the set it >= 0}Copy the code

The cumulative

Kotlinlist.sum () // substitute each element in the set into a lambda expression, Kotlinlist. sumBy {it % 2} // Count all elements from the first item to the last item using a function based on the initial value of the lambda expression. Element starts with the first element of the set, Kotlinlist. fold(100) {accumulator, element -> accumulator + element / 2} FoldRight (100) {accumulator, element -> accumulator + element / 2} The initial value of accumulator is the first element of the collection. Kotlinlist. reduce {accumulator, element -> accumulator + element / 2} The initial value of Accumulator is the last element of the collection, Kotlinlist. reduceRight {accumulator, element -> accumulator + element / 2}Copy the code

traverse

// Iterate over all elements kotlinlist.foreach {print(it)} / / the sameforEach, just can get the index of the element at the same time. KotlinList forEachIndexed {index, value - > println ("position $index contains a $value")}Copy the code

Maximum minimum

// Returns the largest element in the set, or null kotlinlist.max () if the set is empty; // Returns the element in the set that maximizes the value returned by the lambda expression, MaxBy {it} // Returns the smallest element in the set. If the set is empty, null kotlinlist.min () // Returns the element in the set that minimized the value returned by the lambda expression. Return null kotlinlist. minBy {it}Copy the code

filter

Drop (2) // Return a new List, remove the first n elements of the set kotlinlist.droplast (2) // return a new List, remove the first n elements of the set kotlinlist.droplast (2) // remove the first n elements of the set kotlinlist.droplast (2) // return a new List, remove the set criteria (lambda returnstrueDropWhile {it > 3} // Returns a new list, removing the conditions in the collection (lambda returnstrue) kotlinlist. dropLastWhile {it > 3}Copy the code

Sort & reverse

val list = listOf(1, 2, 3, 4, 5, 3) list.reversed() // Return a new set of reversed elements list.sorted() // Return a new set of ascending sorted elements list.sortedby {// replace each element with a lambda expression, Order descending {it*2} list.sortedbydescending ();Copy the code

Merge & decompose

Val list = listOf(1, 2, 3, 4, 5, 6) val list = listOf(5, 6, 7, 8, 9, 0) Return a new collection // Essentially call list.plus(list2) list + list2 // split a given collection into two lists, one of which is returned after the lambda expression is insertedtrueThe other list is returned after substitutionfalseVal (list3, list4) = list.partition {it % 2 == 0} // Return a list of pairs, each pair consisting of two sets of elements with the same index val pairList: List<Pair<Int, Int>> = list.zip(list2) // Unzip Splits a List of pairs into two lists val (list5, list6) = pairlist.unzip ()Copy the code

Kotlin collections are converted to arrays

When we declare a collection, we can convert the collection into the corresponding array by calling the corresponding higher-order function of the collection class. The collection class provides toIntArray(), toDoubleArray(), toFloatArray(), toBetArray(), toTypedArray and other higher-order functions to handle.

Kotlin arrays are converted to collections

In Kotlin, sets can be divided into immutable sets and mutable sets. We declare a collection or array that can be converted to a collection of the corresponding type. Call toXXX() to convert to an immutable collection. Call toMutableXXX() to convert to a mutable collection. The collection class provides toList(), toMutableList(), toSet(), toMutableSet(), toHashSet(), toMap() and other higher-order functions to handle

Such as:

Well, that’s all for today. There’s still a long way to go to learn Kotlin. A new language requires patience

Recommend a few places to study:

Official website documents:

http://kotlinlang.org/

Runoob Chinese document

http://www.runoob.com/kotlin/kotlin-loop-control.html

To read more

Kotlin Development Journey “A” – Beginners Kotlin foundation essential

My Android Refactoring Tour: Plugins

20+ great Android open source projects

Kotlin has become a level 1 Language for Android development — this time you can’t miss it

Believe in yourself, there is nothing impossible, only unexpected

It’s not just technology that’s gained here!