Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 242
GeekyTrash Avatar asked Jun 21 '13 22:06

GeekyTrash


People also ask

How do I add elements to a List in Groovy?

Groovy - add() Append the new value to the end of this List. This method has 2 different variants. boolean add(Object value) − Append the new value to the end of this List.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

What is array in Groovy?

An Array is an object that contains elements of similar data type. Groovy reuses the list notation for arrays, but to make such literals arrays, you need to explicitly define the type of the array through coercion or type declaration. You can also create multi-dimensional arrays.


2 Answers

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.

like image 112
Jake Sellers Avatar answered Oct 16 '22 10:10

Jake Sellers


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.

like image 30
bdkosher Avatar answered Oct 16 '22 10:10

bdkosher