Issue Details (XML | Word | Printable)

Key: GROOVY-1635
Type: Improvement Improvement
Status: Closed Closed
Resolution: Fixed
Priority: Major Major
Assignee: Paul King
Reporter: Marc Palmer
Votes: 0
Watchers: 0
Operations

If you were logged in you would be able to see more operations.
groovy

Improve docs for Collection.groupBy and add new Collection.collate(Closure) [Small breaking change]

Created: 03/Jan/07 02:20 PM   Updated: 23/Dec/07 12:25 PM
Component/s: None
Affects Version/s: 1.0
Fix Version/s: 1.5.2

Time Tracking:
Not Specified


 Description  « Hide
The documentation for Collection.groupBy is a little ambiguous in that it does not make it absolutely clear that the return value is a Map of keys pointing to values that are ArrayLists.

A new method, Collection.collate(Closure) would be a nice addition, to allow collation of a collection of objects into a map keyed on some value provided by a closure, without returning a List for every value. This might be implemented so:

java.util.Map collate(Closure collator) {
    def result = [:]
    this.each() {
         result[collator.call(it)] = it
    }
}


 All   Comments   Work Log   Change History      Sort Order: Ascending order - Click to sort in descending order
Paul King added a comment - 23/Dec/07 12:41 AM - edited
There was already a groupBy for collections and one for maps. Rather than introduce a collate() method I rejigged the existing groupBy on Maps. This seemed to be the most consistent thing to do. I hope this yields what you wanted. The doco has also been improved.

The end result is the following:

// Collection.groupBy
def a = ['ax', 'ay', 'az', 'bx', 'by', 'bz'].groupBy{ it[0] }
assert a == [b:['bx', 'by', 'bz'], a:['ax', 'ay', 'az']]

def z = [Clark:'London', Sharma:'London', Maradona:'LA', Zhang:'HK', Ali:'HK', Liu:'HK']
// Map.groupBy
println z.groupBy{ it.value }
// => [LA:[Maradona:LA], HK:[Zhang:HK, Liu:HK, Ali:HK], London:[Sharma:London, Clark:London]]

// Map.groupEntriesBy
println z.groupEntriesBy{ it.value }
// => [LA:[Maradona=LA], HK:[Zhang=HK, Ali=HK, Liu=HK], London:[Clark=London, Sharma=London]]