1. Traversal of The Kotlin set can be done in the following ways:
1, use.. Keyword, including the right border for (I in 1.. {//print (" $I ") {//print (" $I ") { For (I in 1 until 10) {//print 1 2 3 4 5 6 7 8 9 print(" $I ")} 3 For (I in 10 downTo 1) {//print 10 9 8 7 6 5 4 3 2 1 print(" $I ")} 4 Step 2) {//print ($I, $I, $I, $I, $I, $I)} Print (" $it")} val list = arrayListOf<String>("1", "2", "3", "4", "1", "2", "3", "4", "5", "6", "7", "8") Through the in traverse the for keyword (STR in the list) {/ / print STR = 1 | | STR = 2 STR = 3 | STR = 4 | STR = 5 | | STR = 6 STR = 7 | | STR = 8 Print (" STR = $STR | ")} 7, through the in keyword and withIndex traversal () function, Get set index and set value for ((index, str) in list.withIndex()) { //print index = 0 str 1 | index = 1 str 2 | index = 2 str 3 | index = 3 str 4 | index = 4 str 5 | index = 5 str 6 | index = 6 str 7 | index = 7 str 8 | print("index = $index str $str | ") }Copy the code
2. Set operator
Filter: filters out the specified elements. Map: converts the filtered elements to the specified values. Reduce: combines the last result with the current result
val listStr = arrayOf("a", "p", "5", "9", "g", "k", "0") val listInt = arrayOf(4, 7, 1, 3, 7, 9, 0, 2) fun main(args: Array<String>) {listint. filter {it < liststr.size}. Map {// Get the value of the index from listStr listStr[it] }.reduce { acc, I - > / / print the acc = g I = p = gp I = 9 | | acc acc = gp9 I = a | acc = gp9a | I = 5 print (" acc = $acc I = $I | ") / / merge, Join acc and I into one value "$acc$I "}. Also {println("it $it")}}Copy the code
3. Custom operators
The following code customizes a collection-specific convert operator to + 1 for each element in the list
fun main(args: Array<String>) { action() } fun action() { val list = listOf(1, 2, 3, 4, 5, 6, List. Convert {it + 1}. ForEach {print(it)}} /** * * The top layer of the Collection is "Public interface Collection<out E> : Iterable<E> ", * that is, the collection implements the Iterable interface, Convert */ inline fun <T, E> Iterable<T>.convert(action: (T) -> E): Iterable<E> {// define a MutableList val list: MutableList<E> = mutableListOf() List. Add (action(item)) // Return list}Copy the code