More Than Five
More Than Five

Reputation: 10419

Using groupBy in Groovy

I have a list of Users as

def items = [[name:"tony", age:4], [name:"tony", age: 5], [name:"alan", age:16]]

I want to group them by name so, but only want the age in list so I want

["tony": [4, 5], "alan": [16]]

When I do

def groups = items.groupBy {it.name}

I get: [tony:[[name:tony, age:4], [name:tony, age:5]], alan:[[name:alan, age:16]]]

So still a bit more work to do to get what I want. Any tips?

Upvotes: 2

Views: 1904

Answers (2)

injecteer
injecteer

Reputation: 20699

you can also do it in 1 loop instead of 2:

def items = [[name:"tony", age:4], [name:"tony", age: 5], [name:"alan", age:16]]
def groupped = items.inject( [:].withDefault{ [] } ){ res, curr ->
  res[ curr.name ] << curr.age
  res
}

Upvotes: 5

Opal
Opal

Reputation: 84756

Try:

def items = [[name:"tony", age:4], [name:"tony", age: 5], [name:"alan", age:16]]
def t = items.groupBy { it.name }.collectEntries { [(it.key):(it.value*.age)] }
assert t == ['tony':[4,5],'alan':[16]]

Upvotes: 5

Related Questions