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