Home > Blockchain >  How to assign variable an alternative value if first assigned value is not present in groovy?
How to assign variable an alternative value if first assigned value is not present in groovy?

Time:12-13

I have a situation where I would like to get the output of a readJson and assign it to the variable but I would like to check if different key is present in case first one is not present. Here if key "Name" is not present then I would like to check if "address" is present and add it as collection. followig works for key Name" but I would like to check for "address" in case there is no "Name kry in json object

def originals = readJSON text: sourceStagesText        
  originalconfign = originals.collectEntries { [(it.Name):it] }.asImmutable()

I tired using || operator but it gives true and false value, instead of true or false how can I assign the value of the command that gives the value to the variable for example

 originalconfign = (originals.collectEntries { [(it.Name):it] }.asImmutable() || originals.collectEntries { [(it.address):it] }.asImmutable())

how can I assign the value to originalconfign if it finds Name to name and if it does not then to the address?

CodePudding user response:

This corresponds to your code and just a bit shorter:

originalconfig = originals.collectEntries { [it.Name,it] }.asImmutable() ?: originals.collectEntries { [it.address,it] }.asImmutable()

I think there's an issue in your logic. The second part will work only if first returns null or empty map. But second will always return an empty map if first one is empty...

CodePudding user response:

I solved it with if else statment but please let me know if anyone have better short option to acheive this:

if (originals.collectEntries { [(it.Name):it] }.asImmutable()){
originalconfig = originals.collectEntries { [(it.Name):it] }.asImmutable()
} else {
originalconfig = originals.collectEntries { [(it.address):it] }.asImmutable()
}
  • Related