How Do You Iterate through Data Members (the Individual Components) of a Groovy Object?

Problem scenario
You have an object that you want to sequentially pass through.  That is, you want to print either the value or the key/name and value pair of every member data item of the object.  How do you print every individual data member of a given object in Groovy?

Solution
Invoke the ".properties.each" keyword.  This built-in feature will allow you to do just this.  There is one "if" condition you will use to avoid printing the "class=class ..." feature.

Here is an example (the code starts with "@groovy..." and ends with "}"):

@groovy.transform.Canonical
class Program {
    String mem1 = ""
    String mem2 = ""
    String mem3 = ""
    String mem4 = ""
    String mem5 = ""
    String mem6 = ""
    String mem7 = ""
    String mem8 = ""
    String mem9 = ""
}

programsv1 = new Program( "1", "2", "3", "4", "5", "6", "7", "8", "9")

programsv1.properties.each { name, value ->
    if (name != 'class') {
       println "${name}, ${value}" }
     }

If you want it sorted, use the slightly more verbose option of ".sort{ it.key }" in between the "properties" and ".each".  Here is an example:

@groovy.transform.Canonical
class Program {
    String mem1 = ""
    String mem2 = ""
    String mem3 = ""
    String mem4 = ""
    String mem5 = ""
    String mem6 = ""
    String mem7 = ""
    String mem8 = ""
    String mem9 = ""
}

programsv1 = new Program( "1", "2", "3", "4", "5", "6", "7", "8", "9")

programsv1.properties.sort{ it.key }.each { name, value ->
    if (name != 'class') {
       println "${name}, ${value}" }
     }

Leave a comment

Your email address will not be published.