Richie
Richie

Reputation: 5189

Add to Map in Groovy

In groovy I've got the following...

    def response = [
        modifications: []
    ]

I want to add to this map dynamically so that it ends up like this....

    def response = [
        modifications: [
            userKnown :[
                type: 'Boolean',
                value: userKnown?.toBoolean()
            ]
        ]
    ]

I've tried to do that using this code below...

    if (userKnown){
        def userKnownVariable = [
            userKnown :[
                type: 'Boolean',
                value: userKnown?.toBoolean()
            ]
        ]
        response.modifications << userKnownVariable
    }

But I don't quite end up with what I'm after. Can someone help me with what I'm doing wrong.

thanks

Upvotes: 5

Views: 20322

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

You are mixing two things in given example. modifications in your map is type of List when you use [] and you expect to have a Map instead. To instantiate a map this way you have to use [:]

def response = [
    modifications: [:]
]

def userKnown = [
    userKnown: [
        type: 'Boolean',
        value: true
    ]    
]

response.modifications << userKnown

assert response == [modifications: [userKnown: [type: 'Boolean', value: true]]]

One thing worth mentioning. Consider using List in your example. Adding a new keys to a map may sound reasonable in some cases, although it has one significant issue - the order of every key in modifications is not deterministic, it depends on the map implementation (HashMap, TreeMap etc.). From business logic point of view it looks like you are trying to get an information about all modifications that were applied/added. List in this case would be a better option - you can track the order in which every modification were applied and if you are using this response on the frontend side - it will be easier to iterate over a list and display every result.

Upvotes: 10

Related Questions