KIC KIC - 3 years ago 245
Groovy Question

groovy transform list into map using a groupBy max

Ok, this is a rather simple thing but I am not able to figure this out. I have a groovy list with some objects in it like:

def listOfTings = [
["type": "A", "value": 1],
["type": "B", "value": 3],
["type": "A", "value": 2],
["type": "B", "value": 2]

and I want to get a map out of it like groupBy(type) max(value):

["A": 2, "B": 3]

But I can not find a groupBy method and I have not figured it out using
. Is there some standard way to achieve such a result?

Answer Source

Try following:

listOfTings.groupBy { it.type }.collectEntries { [(it.key): it.value.max { it.value }.value] }

First groupBy will create a map of lists grouped by type field:

[A:[[type:A, value:1], [type:A, value:2]], B:[[type:B, value:3], [type:B, value:2]]]

Next, collectEntries with it.value.max { it.value } will pick single entry with maximum value field:

[A:[type:A, value:2], B:[type:B, value:3]]

Picking value with it.value.max { it.value }.value will extract only a value field instead of whole entry:

[A:2, B:3]

Hope it helps :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download