kotlin 循环技巧

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...")
}

谢谢观赏!!!!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不求人€

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值