GeekyTrash
GeekyTrash

Reputation: 51

How to add items to an array one by one in groovy language

I´m developing a grails app, and I already have a domain class "ExtendedUser" wich has info about users like: "name", "bio", "birthDate". Now I´m planning to do statistics about user´s age so I have created another controller "StatisticsController" and the idea is to store all the birthDates in a local array so I can manage multiple calculations with it

class StatisticsController {
//    @Secured(["ROLE_COMPANY"])
    def teststat(){
        def user = ExtendedUser.findAll()   //A list with all of the users
        def emptyList = []    //AN empty list to store all the birthdates
        def k = 0
        while (k<=user.size()){
            emptyList.add(user[k].birthDate) //Add a new birthdate to the emptyList (The Error)
            k++
        }
        [age: user]
    }
}

When I test, it shows me this error message: Cannot get property 'birthDate' on null object So my question is how is the best way to store all the birthdates in an single array or list, so I can make calculations with it. Thank you

Upvotes: 5

Views: 38618

Answers (3)

bdkosher
bdkosher

Reputation: 5883

I would use this approach:

def birthDates = ExtendedUser.findAll().collect { it.birthDate }

The collect method transforms each element of the collection and returns the transformed collection. In this case, users are being transformed into their birth dates.

Upvotes: 4

Jake Sellers
Jake Sellers

Reputation: 2439

I prefer to .each() in groovy as much as possible. Read about groovy looping here.

For this try something like:

user.each() {
    emptylist.push(it.birthdate) //'it' is the name of the default iterator created by the .each()
}

I don't have a grails environment set up on this computer so that is right off the top of my head without being tested but give it a shot.

Upvotes: 11

tim_yates
tim_yates

Reputation: 171054

Can you try:

List dates = ExtendedUser.findAll().birthDate

Upvotes: 0

Related Questions