deewreck
deewreck

Reputation: 133

iterating map of map in groovy

I have a map of type Map<Boolean,Map<String,String>>

how can i iterate over them. I have following code written but is there any better way to do it in 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()

update :

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"
])

while creating this map i am getting

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

what could be the reason?? i think i have created map properly.

Upvotes: 0

Views: 303

Answers (1)

injecteer
injecteer

Reputation: 20699

  1. Do not use implicit it variable in nested loops.
  2. Do not use String concatenation in debug outputs, use GString interpolation instead.

I would start re-writing your code so:

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"
    }
}

Answer to update:

If you want to use constants as keys in Map literal, you have to put them in brackets ():

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

Upvotes: 1

Related Questions