Kotlin for 循环写法整理
生活随笔
收集整理的這篇文章主要介紹了
Kotlin for 循环写法整理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、Map 的 in 運算符方式:
fun forMap1() {val map = hashMapOf<String, String>("name" to "Hili", "age" to "93")for ((k, v) in map) {println("$k -> $v")} }輸出:
name -> Hili age -> 93?
?
2、List 的 in 運算符方式:
fun forList1() {val list = listOf("apple", "banana", "kiwifruit")for (item in list) {println(item)} }輸出:
apple banana kiwifruit?
?
3、List 的 in 運算符方式,帶上數據類型:
fun forList2() {val list = listOf("apple", "banana", "kiwifruit")for (item: String in list) {println(item)} }輸出:
apple banana kiwifruit?
?
4、List 的 indices 索引方式:
fun forList3() {val list = listOf("apple", "banana", "kiwifruit")for (index in list.indices) {val str = "item at $index is ${list[index]}"println(str)} }輸出:
item at 0 is apple item at 1 is banana item at 2 is kiwifruit?
?
5、List 的 withIndex() 庫函數方式:
fun forList4() {val list = listOf("apple", "banana", "kiwifruit")// 庫函數 withIndex() 獲取索引for ((i, v) in list.withIndex()) {val str = "the element at $i is $v"println(str)} }輸出:
the element at 0 is apple the element at 1 is banana the element at 2 is kiwifruit?
?
6、Array 的 in 運算符方式(同 List):
fun forArray1() {val array = arrayOf("java", "c plus plus", "kotlin", "python")for (item in array) {println(item)} }輸出:
java c plus plus kotlin python?
?
7、Array 的 in 運算符方式,帶上數據類型(同 List):
fun forArray2() {val array = arrayOf("java", "c plus plus", "kotlin", "python")for (item: String in array) {println(item)} }輸出:
java c plus plus kotlin python?
?
8、Array 的 indices 索引方式(同 List):
fun forArray3() {val array = arrayOf("java", "c plus plus", "kotlin", "python")for (index in array.indices) {val str = "item at $index is ${array[index]}"println(str)} }輸出:
item at 0 is java item at 1 is c plus plus item at 2 is kotlin item at 3 is python?
?
9、Array 的 withIndex() 庫函數方式(同 List):
fun forArray4() {val array = arrayOf("java", "c plus plus", "kotlin", "python")// 庫函數 withIndex() 獲取索引for ((i, v) in array.withIndex()) {val str = "the element at $i is $v"println(str)} }輸出:
the element at 0 is java the element at 1 is c plus plus the element at 2 is kotlin the element at 3 is python?
?
10、.. (rangeTo()) 方式:
fun forRange1() {for (item in 1..5) {print(item)} }輸出:
1 2 3 4 5?
?
11、.. (rangeTo())? step 方式:
fun forRange2() {for (item in 0..10 step 3) {print(item)} }輸出:
0 3 6 9?
?
12、.. (rangeTo())? downTo?方式:
fun forRange3() {for (item in 10 downTo 0) {print(item)} }輸出:
10 9 8 7 6 5 4 3 2 1 0?
?
13、.. (rangeTo())? downTo step方式:
fun forRange4() {for (item in 10 downTo 0 step 3) {print(item)} }輸出:
10 7 4 1?
?
14、until [閉,開) 區間方式:
fun forRange5() {for (item in 0 until 10) {print(item)} }輸出:
0 1 2 3 4 5 6 7 8 9?
總結
以上是生活随笔為你收集整理的Kotlin for 循环写法整理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux中防火墙firewalld
- 下一篇: 对象存储s3cmd使用手册