英文:
Groovy GroupBy Variable KeySet
问题
List<Map> people = [
[
Sex: "Male",
Age: 30,
Job: "Programmer",
Name: "Boris"
],
[
Sex: "Female",
Age: 30,
Job: "Programmer",
Name: "Jennifer"
],
[
Sex: "Male",
Age: 40,
Job: "Web Designer",
Name: "Bob"
],
[
Sex: "Female",
Age: 20,
Job: "Database Admin",
Name: "Alice"
]
]
List results = []
if (people.groupBy({it.Sex}, {it.Age}) != groupBySpecifiedCols(people, ["Sex", "Age"])) {
return "Failed 1"
}
if (people.groupBy({it.Sex}, {it.Age}, {it.Job}) != groupBySpecifiedCols(people, ["Sex", "Age", "Job"])) {
return "Failed 2"
}
def groupBySpecifiedCols(List<Map> data, List<String> columns) {
// IMPLEMENT HERE
return null
}
return "Success!"
英文:
I am struggling with using groovy groupBy
I need to support grouping a dataset by a variable key set.
I have written a test to explain my predicament, and would love some help understanding how to implement it:
https://groovyconsole.appspot.com/script/5155615986941952
List<Map> people = [
[
Sex: "Male",
Age: 30,
Job: "Programmer",
Name: "Boris"
],
[
Sex: "Female",
Age: 30,
Job: "Programmer",
Name: "Jennifer"
],
[
Sex: "Male",
Age: 40,
Job: "Web Designer",
Name: "Bob"
],
[
Sex: "Female",
Age: 20,
Job: "Database Admin",
Name: "Alice"
]
]
List results = []
if(people.groupBy({it.Sex}, {it.Age}) != groupBySpecifiedCols(people, ["Sex", "Age"])){
return "Failed 1"
}
if(people.groupBy({it.Sex}, {it.Age}, {it.Job}) != groupBySpecifiedCols(people, ["Sex", "Age", "Job"])){
return "Failed 2"
}
def groupBySpecifiedCols(List<Map> data, List<String> columns){
// IMPLEMENT HERE
return null
}
return "Success!"
答案1
得分: 2
实际上,我认为我刚刚解决了这个问题,在经过数小时的沮丧后,原来它很简单:
def groupBySpecifiedCols(List<Map> data, List<String> columns){
List<Closure> groupByClosures = []
columns.each{ column ->
groupByClosures << { it[column] }
}
return data.groupBy(groupByClosures)
}
**编辑** 如评论中所指出,可能有一种更简洁的方式:
def groupBySpecifiedCols(List<Map> data, List<String> columns){
return data.groupBy(columns.collect{ col -> ((Closure){ it[col] })})
}
英文:
Actually I think I just solved it, after hours of frustration it turned out simple:
def groupBySpecifiedCols(List<Map> data, List<String> columns){
List<Closure> groupByClosures = []
columns.each{ column ->
groupByClosures << { it[column] }
}
return data.groupBy(groupByClosures)
}
EDIT as pointed out in comments, there is a potentially more concise way:
def groupBySpecifiedCols(List<Map> data, List<String> columns){
return data.groupBy(columns.collect{ col -> ((Closure){ it[col] })})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论