Categories: java, groovy, closures

Groovy GroupBy Variable KeySet

1 answer

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!"​​​​ 

All answers to this question, which has the identifier 61118351

The best answer:

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] })}) } 

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type com.google.firebase.iid.zzav is referenced as an interface from com.google.firebase.messaging.zzd”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data