Groovy 中如何遍历集合

张开发
2026/4/21 3:04:24 15 分钟阅读

分享文章

Groovy 中如何遍历集合
在 Groovy 中遍历集合List、Map、Set非常灵活。虽然你可以使用传统的 Javafor循环但 Groovy 提供了更简洁、更具表达力的闭包方法这也是 Groovy 开发中最常用的方式。以下是几种主流的遍历方式1. 使用each闭包最推荐这是 Groovy 中最地道、最常用的遍历方式。它适用于 List、Map 和 Set。遍历 List当只有一个参数时闭包内部默认使用it来指代当前元素。deffruits[Apple,Banana,Orange]// 简写使用默认的 itfruits.each{println吃一个:$it}// 显式写法指定参数名fruits.each{fruit-println水果名:$fruit}遍历 Map遍历 Map 时通常会接收两个参数key 和 value或者接收一个Map.Entry对象。defperson[name:Tom,age:18,city:Beijing]// 方式一直接接收 key 和 valueperson.each{key,value-println$key$value}// 方式二接收 entry 对象person.each{entry-println${entry.key}:${entry.value}}2. 带索引的遍历eachWithIndex如果你需要知道当前元素的下标索引使用eachWithIndex比在普通each里维护一个计数器要优雅得多。defletters[a,b,c]letters.eachWithIndex{item,index-println第$index个元素是:$item}3. 传统的for循环作为 Java 开发者你可能习惯了这种写法。Groovy 完全支持但在纯 Groovy 代码中大家更倾向于用each因为它更符合函数式编程的风格。deflist[1,2,3]// 标准 Java 风格for(inti0;ilist.size();i){println list[i]}// Groovy 简化的 for-in 循环for(iteminlist){println item}4. 进阶不仅仅是遍历在 Groovy 中我们很少单纯为了“打印”而遍历。通常我们会结合其他闭包方法来进行过滤或转换这比单纯的遍历更高效方法用途示例findAll遍历并筛选符合条件的元素list.findAll { it 2 }collect遍历并转换每个元素类似 Stream maplist.collect { it * 2 }find遍历直到找到第一个符合条件的元素即停止list.find { it 2 }示例组合使用defnumbers[1,2,3,4,5]// 找出偶数并翻倍存入新集合defresultnumbers.findAll{it%20}.collect{it*10}println result// 输出: [20, 40] 总结建议日常开发无脑用each代码最简洁。需要下标用eachWithIndex。数据处理优先考虑findAll或collect而不是在each里手动做 if 判断和 add 操作。

更多文章