1. 简洁的区间遍历
for (variable in start..end) : 使用..操作符定义一个左闭右闭区间(包含start和end),适用于递增遍历。
for (i in 1..10) {
println(i)
}
for (variable in start until end) : 使用until定义一个左闭右开区间(包含start但不包含end),同样用于递增遍历。
for (j in 0 until array.size) {
println(array[j])
}
2. 步长控制
for (variable in start..end step increment) : 添加step关键字指定每次循环递增的值。
for (k in 1..100 step 5) {
println(k)
}
3. 逆序遍历
for (variable in end downTo start) : 使用downTo从end到start进行递减遍历。
for (n in 10 downTo 1) {
print("$n ")
}
4. 遍历集合与数组
for (element in collection) : 直接遍历集合或数组元素,无需索引。
val list = listOf("apple", "banana", "cherry")
for (fruit in list) {
println(fruit)
}
5. 多重循环
嵌套循环:可以轻松地将一个循环置于另一个循环内部,实现二维或其他多维数据结构的遍历。
for (i in 1..3) {
for (j in 1..3) {
println("($i, $j)")
}
}
6. forEach函数与lambda表达式
对于支持迭代的集合类,可以使用forEach函数配合lambda表达式进行简洁的遍历。
list.forEach {
println(it)
}
7. withIndex扩展函数
当需要同时访问集合元素及其索引时,可以使用withIndex()扩展函数。
list.withIndex().forEach { (index, value) ->
println("Index: $index, Value: $value")
}
8. takeWhile与dropWhile
对于流式处理,可以利用takeWhile获取满足条件的元素序列的前缀,或使用dropWhile丢弃满足条件的元素序列的前缀。
val numbers = listOf(1, 2, 3, 4, 5, 4, 3, 2, 1)
numbers.takeWhile { it < 4 }.forEach { println(it) } // 输出: 1, 2, 3
numbers.dropWhile { it < 4 }.forEach { println(it) } // 输出: 4, 5, 4, 3, 2, 1
9. repeat函数
用于固定次数的循环,传入次数作为参数,无需显式声明循环变量。
repeat(5) {
println("Repeating...")
}
谢谢观赏!!!!