Varad Chemburkar
Varad Chemburkar

Reputation: 478

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

Upvotes: 5

Views: 17247

Answers (3)

Newaz Sharif Amit
Newaz Sharif Amit

Reputation: 197

list.groupBy{ it[1] }.collect { key,value -> value.get(0) }

Upvotes: -1

Roger Glover
Roger Glover

Reputation: 3256

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

list.groupBy{ it[1] }.collectEntries{ k, v -> [(k):v*.get(0)] }

Upvotes: 9

tim_yates
tim_yates

Reputation: 171084

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
}

Upvotes: 6

Related Questions