Richie
Richie

Reputation: 5199

how to join list of maps in groovy

If i have two list of maps in groovy...

def x = [ [a:1, b:2], [a:1, b:3], [a:2, b:4] ]
​def y = ​[ [f:10, b:2, g:7], [f:100, b:3, g:8], [f:20, b:4, g:9] ]

How can I join them based on a particular attribute. In the above example the values for b.

Desired result is...

[a:1, b:2, f:10, g:7]
[a:1, b:3, f:100, g:8]
[a:2, b:4, f:20, g:9]

I tried this but it's not exactly what I'm after.

def z = (x + y).groupBy { it.b }
z.each{ k, v -> println "${k}:${v}" }

thanks

Upvotes: 2

Views: 3003

Answers (2)

tim_yates
tim_yates

Reputation: 171084

Can't you just do:

[x,y].transpose().collect { a, b -> a + b }

Upvotes: 1

Rao
Rao

Reputation: 21369

You should be able to get the desired result with:

println (x + y).groupBy { it.b }.collect{it.value}.collect{item -> def m = [:] ; item.collect{ m +=it}; m }

You can quickly try it online demo

Upvotes: 3

Related Questions