groovy

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

Details

  • Type: Improvement Improvement
  • Status: Closed Closed
  • Priority: Major Major
  • Resolution: Fixed
  • Affects Version/s: 1.0
  • Fix Version/s: 1.5.2
  • Component/s: None
  • Labels:
    None
  • Number of attachments :
    0

Description

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

Activity

Hide
Paul King added a comment - - 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]]
Show
Paul King added a comment - - 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]]

People

Vote (0)
Watch (0)

Dates

  • Created:
    Updated:
    Resolved: