Could you type the name of the variable in the Groovy list, not the value

If I got a list in Groovy containing 2 or more variables with some value, and I want to see if it contains the given text string, I do 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 name of the variable containing the text. Is this possible with a list or do I need to make a map?

+5
source share
2 answers

You need to use Map as a 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" } } 
+4
source

If you run it as a Groovy script, you can use the binding archive instead of a list of variables, but you need to assign variables without def (so that they become part of the binding). Sort of:

 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' 
+4
source

Source: https://habr.com/ru/post/1399133/


All Articles