If I got a list in Groovy containing 2 or more variables with some value, and I want to see if it contains a given text string I'm doing the following:
def msg = '''
Hello Mars!
'''
def msg1 = '''
Hello world!
'''
def list = [msg, msg1]
list.findAll { w ->
if(w.contains("Hello"))
{
println w
}
else
{
println "Not there"
}
}
But instead of printing the value I would like to print the variable name that contains the text. Is that possible with a list or do I need to make a map?
You need to use a Map
, because mapping from keys to values.
def msg = '''
Hello Mars!
'''
def msg1 = '''
Hello world!
'''
def map = [msg: msg, msg1: msg1]
map.findAll { key, value ->
if (value.contains("Hello")) {
println key
}
else {
println "Not there"
}
}
If you are running this as a Groovy script, you may use the binding
archive instead of a list of variables, but you need to assign the variables without the def
(so they become part of the binding). Something like:
aaa = 'Hello World!'
bbb = 'Goodbye all!'
ccc = 'Hello Mars!'
this.binding.variables.each { var ->
if (var.value ==~ /Hello.*/)
println "$var.key contains 'Hello'"
}
Output:
aaa contains 'Hello'
ccc contains 'Hello'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With