1. 简介

在本篇教程中,我们将介绍如何使用 Groovy 提供的标准语言特性来遍历一个 Map,包括 eacheachWithIndexfor-in 循环等方法。

2. 使用 each 方法遍历

假设我们有如下定义的 Map:

def map = [
    'FF0000' : 'Red',
    '00FF00' : 'Lime',
    '0000FF' : 'Blue',
    'FFFF00' : 'Yellow'
]

我们可以使用 each 方法配合闭包进行遍历:

map.each { println "Hex Code: $it.key = Color Name: $it.value" }

当然,为了提高可读性,我们可以给 entry 变量起个名字:

map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" }

如果你更喜欢分别处理 key 和 value,也可以将它们分开写在闭包参数中:

map.each { key, val ->
    println "Hex Code: $key = Color Name $val"
}

注意:Groovy 中通过字面量语法创建的 Map 是有序的。 所以输出顺序会和你定义时保持一致。

3. 使用 eachWithIndex 获取索引

有时候我们需要知道当前元素的索引位置。例如,我们想让每一行交替缩进显示,就可以使用 eachWithIndex 方法:

map.eachWithIndex { entry, index ->
    def indent = ((index == 0 || index % 2 == 0) ? "   " : "")
    println "$index Hex Code: $entry.key = Color Name: $entry.value"
}

each 类似,我们也可以直接使用 key 和 value 作为参数:

map.eachWithIndex { key, val, index ->
    def indent = ((index == 0 || index % 2 == 0) ? "   " : "")
    println "$index Hex Code: $key = Color Name: $val"
}

⚠️ 注意:当使用三个参数(key, value, index)时,Groovy 会自动识别最后一个是索引。

4. 使用 for-in 循环遍历

如果你更偏向命令式编程风格,也可以选择使用 for-in 循环来遍历 Map:

for (entry in map) {
    println "Hex Code: $entry.key = Color Name: $entry.value"
}

这种方式看起来更像传统 Java 风格,但在 Groovy 中依然简洁高效。

5. 总结

在这篇简短的教程中,我们学习了如何使用 Groovy 提供的 eacheachWithIndex 方法以及 for-in 循环来遍历 Map。

示例代码可以在 GitHub 上找到。


原始标题:A Quick Guide to Iterating a Map in Groovy