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"]]}
You could take your intermediate result and just transform it one step further:
list.groupBy{ it[1] }.collectEntries{ k, v -> [(k):v*.get(0)] }
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With