简体   繁体   English

在Groovy中循环Map?

[英]Loop through Map in Groovy?

I have a very simple task I am trying to do in Groovy but cannot seem to get it to work.我有一个非常简单的任务,我想在 Groovy 中做,但似乎无法让它工作。 I am just trying to loop through a map object in groovy and print out the key and value but this code does not work.我只是想遍历 groovy 中的 map object 并打印出键和值,但此代码不起作用。

// A simple map
def map = [
        iPhone : 'iWebOS',
        Android: '2.3.3',
        Nokia  : 'Symbian',
        Windows: 'WM8'
]

// Print the values
for (s in map) {
    println s + ": " + map[s]
}

I am trying to get the output to look like this:我想让 output 看起来像这样:

iPhone: iWebOS
Android: 2.3.3
Nokia: Symbian
Windows: WM8

Could someone please elaborate on how to do this??有人可以详细说明如何做到这一点吗?

Quite simple with a closure:闭包非常简单:

def map = [
           'iPhone':'iWebOS',
           'Android':'2.3.3',
           'Nokia':'Symbian',
           'Windows':'WM8'
           ]

map.each{ k, v -> println "${k}:${v}" }

Alternatively you could use a for loop as shown in the Groovy Docs :或者,您可以使用for循环,如Groovy 文档中所示:

def map = ['a':1, 'b':2, 'c':3]
for ( e in map ) {
    print "key = ${e.key}, value = ${e.value}"
}

/*
Result:
key = a, value = 1
key = b, value = 2
key = c, value = 3
*/

One benefit of using a for loop as opposed to an each closure is easier debugging, as you cannot hit a break point inside an each closure (when using Netbeans).使用for循环而不是each闭包的一个好处是更容易调试,因为您不能在each闭包内击中断点(使用 Netbeans 时)。

When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value使用for循环时,s的值是一个Map.Entry元素,意思是可以从s.key中得到键,从s.value中得到值

Another option:另外一个选择:

def map = ['a':1, 'b':2, 'c':3]
map.each{
  println it.key +" "+ it.value
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM