Search code examples
groovy

Given a list of elements that evaluate to boolean values, how do I print the element name and not the value?


Lets say I have some variables that evaluate to either true or false:

firstValue = true
secondValue = false
thirdValue = true

And I put them in a list:

def list = [firstValue, secondValue, thirdValue]

I want to iterate through the list and check if each value returns true or false, if the value is true I want to be able to print the name i.e. firstValue

for (item in list){
    if (item == true){
        println("${item} is true")
    }
}

This is just printing "true is true"


Solution

  • Your list only holds the values (true/false), so it's 'hard' to get the key back.

    Consider using a dictionary, which holds some keys that you can iterate to show both the key and value

    data = {
        "firstValue": True,
        "secondValue": False,
        "thirdValue": True
    }
    
    for key, value in data.items():
        if value:
            print(key, "is true")
    
    firstValue is true
    thirdValue is true
    
    Try it online!

    If you really need a separate list of keys, you can use the following instead of calling items()

    listOfKeys = list(data.keys())
    
    for key in listOfKeys:
        if data[key]: