如何在groovy语言中逐个添加项目到数组

Gee*_*ash 4 arrays grails groovy controller list

我正在开发一个grails应用程序,我已经有一个域类"ExtendedUser",它有关于用户的信息,如:"name","bio","birthDate".现在我打算做关于用户年龄的统计数据,所以我创建了另一个控制器"StatisticsController",其目的是将所有birthDates存储在本地数组中,这样我就可以用它管理多个计算

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]
    }
}
Run Code Online (Sandbox Code Playgroud)

当我测试时,它向我显示了这个错误消息:无法在null对象上获取属性'birthDate'所以我的问题是如何将所有生日存储在单个数组或列表中的最佳方法,因此我可以用它进行计算.谢谢

Jak*_*ers 11

我更喜欢.each()尽可能在groovy中.在这里阅读有关groovy循环的内容.

对于这个尝试类似于:

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

我没有在这台计算机上设置grails环境,所以在没有经过测试的情况下,它就在我的头顶,但是试一试.


tim*_*tes 0

你能试一下吗:

List dates = ExtendedUser.findAll().birthDate
Run Code Online (Sandbox Code Playgroud)