list 如何用groovy语言将项目一一添加到数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17245246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 02:01:34  来源:igfitidea点击:

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

arrayslistgrailsgroovycontroller

提问by GeekyTrash

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

我正在开发一个 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]
    }
}

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

当我测试时,它向我显示了这个错误消息:Cannot get property 'birthDate' on null object 所以我的问题是如何将所有生日存储在单个数组或列表中的最佳方式,以便我可以用它进行计算。谢谢

回答by Jake Sellers

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

我更喜欢 .each() 在 groovy 中尽可能多。在此处阅读有关 groovy 循环的信息

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.

我没有在这台计算机上设置 grails 环境,所以这在我的头顶上没有经过测试,但试一试。

回答by bdkosher

I would use this approach:

我会使用这种方法:

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

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

collect方法转换集合的每个元素并返回转换后的集合。在这种情况下,用户被转换为他们的出生日期。

回答by tim_yates

Can you try:

你能试一下吗:

List dates = ExtendedUser.findAll().birthDate