Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Groovy中使用groupby为map值选择对象字段_Groovy - Fatal编程技术网

如何在Groovy中使用groupby为map值选择对象字段

如何在Groovy中使用groupby为map值选择对象字段,groovy,Groovy,我有一个带有getName()和getYearOfBirth()方法的Person对象的人员列表。我正在使用groupBy对Person对象进行分组。我正在使用groupBy对Person对象进行分组,但我只希望将名称放入地图中,因为Person将来将有许多附加字段。岁月将是关键 class Person { String name int yearOfBirth } def people = [ new

我有一个带有getName()和getYearOfBirth()方法的Person对象的人员列表。我正在使用groupBy对Person对象进行分组。我正在使用groupBy对Person对象进行分组,但我只希望将名称放入地图中,因为Person将来将有许多附加字段。岁月将是关键

    class Person {
        String name
        int yearOfBirth
    }       

    def people = [ 
        new Person(name:"Tom", yearOfBirth:1985),
        new Person(name:"Abigail", yearOfBirth:1987),
        new Person(name:"Joyce", yearOfBirth:1984),
        new Person(name:"James", yearOfBirth:1987),
        new Person(name:"Scott", yearOfBirth:1985),
        new Person(name:"Ruth", yearOfBirth:1984)
    ]           

    //people.groupBy(_.year) mapValues (_ map (_.name))  how to map here?
这是一个

的直接端口,一个解决方案是:

def nameInYear = people.groupBy { it.yearOfBirth }
                       .collectEntries { [ (it.key):it.value.name ] }
assert nameInYear[ 1984 ] == [ 'Joyce', 'Ruth' ]
def namesByYear = [:].withDefault { [] } 
people.each { namesByYear[it.yearOfBirth] << it.name }

assert namesByYear[1985] == ['Tom', 'Scott']
所以,根据他们的出生年份对他们进行分组,得到一张年份->人口地图列表
然后,针对这些分组,收集一张年度地图->姓名列表

另一个更重要的解决方案是:

def nameInYear = people.groupBy { it.yearOfBirth }
                       .collectEntries { [ (it.key):it.value.name ] }
assert nameInYear[ 1984 ] == [ 'Joyce', 'Ruth' ]
def namesByYear = [:].withDefault { [] } 
people.each { namesByYear[it.yearOfBirth] << it.name }

assert namesByYear[1985] == ['Tom', 'Scott']