A Quick Guide to Iterating a Map in Groovy – 在Groovy中迭代地图的快速指南

最后修改: 2019年 2月 20日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this short tutorial, we’ll look at ways to iterate over a map in Groovy using standard language features like eacheachWithIndex, and a for-in loop.

在这个简短的教程中,我们将使用标准的语言特性,如eacheachWithIndex、for-in循环,来看看如何在Groovy中迭代地图。

2. The each Method

2.each方法

Let’s imagine we have the following map:

让我们想象一下,我们有以下地图。

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

We can iterate over the map by providing the each method with a simple closure:

我们可以通过为each方法提供一个简单的闭包来迭代地图:

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

We can also improve the readability a bit by giving a name to the entry variable:

我们还可以通过给入口变量起一个名字来提高一下可读性。

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

Or, if we’d rather address the key and value separately, we can list them separately in our closure:

或者,如果我们愿意分别处理键和值,我们可以在我们的闭包中分别列出它们。

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

In Groovy, maps created with the literal notation are ordered. We can expect our output to be in the same order as we defined in our original map.

在Groovy中,用字面符号创建的地图是有序的。我们可以期望我们的输出与我们在原始地图中定义的顺序相同。

3. The eachWithIndex Method

3.eachWithIndex方法

Sometimes we want to know the index while we’re iterating.

有时我们想在迭代的时候知道index

For example, let’s say we want to indent every other row in our map. To do that in Groovy, we’ll use the eachWithIndex method with entry and index variables:

例如,假设我们想缩进我们地图中的每一行。在Groovy中,我们将使用eachWithIndex方法和entryindex变量来实现这一目的。

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

As with the each method, we can choose to use the key and value variables in our closure instead of the entry:

each方法一样,我们可以选择在我们的闭包中使用keyvalue变量而不是entry

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

4. Using a For-in Loop

4.使用For-in循环

On the other hand, if our use case lends itself better to imperative programming, we can also use a for-in statement to iterate over our map:

另一方面,如果我们的用例更适合命令式编程,我们也可以使用for-in语句来迭代我们的地图。

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

5. Conclusion

5.总结

In this short tutorial, we learned how to iterate a map using Groovy’s each and eachWithIndex methods and a for-in loop.

在这个简短的教程中,我们学习了如何使用Groovy的eacheachWithIndex方法以及一个for-in循环来迭代一个地图。

The example code is available over on GitHub.

该示例代码可在GitHub上获得。