How can I group map values by 2 different criteria to get the outputs below ?
def listOfMaps = [
[name:'Clark', city:'London', hobby: 'chess'], [name:'Sharma', city:'London', hobby: 'design'],
[name:'Maradona', city:'LA', hobby: 'poker'], [name:'Zhang', city:'HK', hobby: 'chess'],
[name:'Ali', city: 'HK', hobby: 'poker'], [name:'Liu', city:'HK', hobby: 'poker'],
[name:'Doe', city:'LA', hobby: 'design'], [name:'Smith', city:'London', hobby: 'poker'],
[name:'Johnson', city: 'London', hobby: 'poker'], [name:'Waters', city:'LA', hobby: 'poker'],
[name:'Hammond', city:'LA', hobby: 'design'], [name:'Rogers', city:'LA', hobby: 'chess'],
]
-
group order : hobby, city
poker London Smith Johnson LA Maradona Waters HK Ali Liu design London Sharma LA Doe Hammond HK chess London Clark LA Rogers HK Zhang -
group order : city, hobby
London poker Smith Johnson design Sharma chess Clark LA poker Maradona Waters design Doe Hammond chess Rogers HK poker Ali Liu design chess Zhang
Edit :
What I really need is the way to iterate to effectively loop through the group structure, and be able to construct the result (group / subgroup / name ).
Something like :
- for each group, print/output the group name;
- for each subgroup inside a group, print/output the subgroup name
- inside each subgroup, print the names.
It would yield the result outlined above.
As a nice aside, I would like to sort the whole data structure (groups and names).
For the first case:
and for the second:
You will end up with the original values in the map rather than just the name, but you will be able to do:
to get the result
btw: This form of
groupByhas only been available since Groovy 1.8.1, so if you’re stuck on an earlier version, this won’t workedit 2
Based on your comment below, you can then do:
This is the same logic as GVdP had in his answer, but I feel using the groupBy with multiple parameters like I have here makes your code more readable and obvious as to its intent