成功最有效的方法就是向有经验的人学习!

Groovy for循环

Groovy循环支持几种方式,由于groovy是完全兼容Java的, 所以第一种就是Java中的循环

第一种

String message = ''
for (int i = 0; i < 5; i++) {
    message += 'Hi '
}

第二种 使用in关键字

a:使用 .. 方式. 在某一范围内()

class ListStudy {
    static void main(String[] args) {
        def x = 0
        for ( i in 0..9 ) {
            x += i
        }
        println(x)
    }
}

b:循环遍历list集合

class ListStudy {
    static void main(String[] args) {
        def x = 0
        for ( i in [0, 1, 2, 3, 4] ) {
            x += i
        }
        println(x)
    }
}

c:遍历数组

class ListStudy {
    static void main(String[] args) {
        def array = (0..4).toArray()
        def x = 0
        for ( i in array ) {
            x += i
        }
        println(x)
    }
}

d:遍历map

class ListStudy {
    static void main(String[] args) {
        def map = ['abc':1, 'def':2, 'xyz':3]
        def x = 0
        for ( e in map ) {
            x += e.value
        }
        println(x)
    }
}

e:遍历map中的value

class ListStudy {
    static void main(String[] args) {
        def map = ['abc':1, 'def':2, 'xyz':3]
        def x = 0
        for ( v in map.values() ) {
            x += v
        }
        println(x)
    }
}

f:遍历字符串中的字符

class ListStudy {
    static void main(String[] args) {
        def text = "abc"
        def list = []
        for (c in text) {
            list.add(c)
        }
        println(list)
    }
}
赞(0) 打赏
未经允许不得转载:陈桂林博客 » Groovy for循环
分享到

大佬们的评论 抢沙发

全新“一站式”建站,高质量、高售后的一条龙服务

微信 抖音 支付宝 百度 头条 快手全平台打通信息流

橙子建站.极速智能建站8折购买虚拟主机

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册