簡體   English   中英

在 groovy 中迭代 map 的 map

[英]iterating map of map in groovy

我有一個 Map<Boolean,Map<String,String>> 類型的 map

我怎樣才能迭代它們。 我編寫了以下代碼,但是在 groovy 中是否有更好的方法來做到這一點?

getTopic(boolean boo){
...
}

def test = { jsonMap ->
    jsonMap.each {
        def topic = it.getKey()
        it.getValue().each{
            println(topic+" "+" "+it.getKey()+" "+it.getValue())
        }
        println "Message sent for cluster " + it.getKey()
    }
}
groovy.lang.MissingMethodException: No signature of method: java.lang.Boolean.plus() is applicable for argument types: (String) values: [ ]
Possible solutions: is(java.lang.Object), split(groovy.lang.Closure), use([Ljava.lang.Object;), wait(), any(), dump()

更新

def prod = new KafkaProducer([
        ProducerConfig.BOOTSTRAP_SERVERS_CONFIG       : "host",
        ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG  : "org.apache.kafka.common.serialization.StringSerializer",
        ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG    : "org.apache.kafka.common.serialization.StringSerializer",
        ProducerConfig.ACKS_CONFIG                    : "all"
])

在創建這個 map 時,我得到了

 Unexpected input: ':' @ line 15, column 55.
   OOTSTRAP_SERVERS_CONFIG       : "hos

可能是什么原因?? 我想我已經正確地創建了 map。

  1. 不要在嵌套循環中使用隱式it變量。
  2. 不要在調試輸出中使用字符串連接,而是使用 GString 插值。

我會開始重寫你的代碼,這樣:

def test = { jsonMap ->
    jsonMap.each{ topic, topicMap ->
        topicMap.each{
            println "$topic $it.key $it.value" // here it's ok to use "it"
        }
        println "Message sent for cluster $topic"
    }
}

更新答案:

如果要在 Map 文字中使用常量作為鍵,則必須將它們放在括號()中:

def prod = new KafkaProducer([
        (ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)       : "host",
        (ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)  : "org.apache.kafka.common.serialization.StringSerializer",
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM