Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group By in Groovy

I have a list of object as follows

[["GX 470","Model"],["Lexus","Make"],["Jeep","Make"],["Red","Color"],["blue","Color"]]

and I want to transform it to

{"Model":["GX 470"],"Make":["Lexus","Jeep"],"Color":["Red", "blue"]}

I tried

list.groupBy{ it[1] }

But that returns me

{"Model":[["GX 470","Model"]],"Make":[["Lexus","Make"],["Jeep","Make"]],"Color":[["Red","Color"],["blue","Color"]]}
like image 334
Varad Chemburkar Avatar asked Dec 19 '22 11:12

Varad Chemburkar


2 Answers

You could take your intermediate result and just transform it one step further:

list.groupBy{ it[1] }.collectEntries{ k, v -> [(k):v*.get(0)] }
like image 152
BalRog Avatar answered Dec 21 '22 00:12

BalRog


That's because groupBy doesn't remove the element it grouped by from the original object, so you get all the original data, just grouped by a key.

You can use inject (and withDefault) for more custom grouping:

list.inject([:].withDefault{[]}) { map, elem ->
    map[elem[1]] << elem[0]
    map
}
like image 40
tim_yates Avatar answered Dec 20 '22 23:12

tim_yates