2

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

Richie
  • 4,989
  • 24
  • 90
  • 177
  • 1
    Possible duplicate of [How to merge two maps in groovy](https://stackoverflow.com/questions/40267591/how-to-merge-two-maps-in-groovy) – cfrick Aug 21 '17 at 08:10
  • Richie, check the solution to see if that helps. – Rao Aug 21 '17 at 08:40

2 Answers2

3

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

Rao
  • 20,781
  • 11
  • 57
  • 77
  • richie, looks you had a [new question](https://stackoverflow.com/questions/45905405/using-transpose-to-merge-lists-in-full-outer-join-style) for the same? But this gives the desired result. Have you checked? – Rao Aug 27 '17 at 14:14
1

Can't you just do:

[x,y].transpose().collect { a, b -> a + b }
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • This variant returns this: [[a:1, b:3], [a:2, b:4], [f:20, b:4, g:9]] instead of [[a:1, b:2, f:10, g:7], [a:1, b:3, f:100, g:8], [a:2, b:4, f:20, g:9]] Why dose it marked as accepted? – Seyf May 12 '22 at 12:29
  • 1
    @Seyf no it doesn't, it returns `[[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 just checked in Groovy 3.0.9 – tim_yates May 12 '22 at 12:36
  • Yes, it was my mistake :( I am so sorry! – Seyf May 12 '22 at 15:41
  • @Seyf no worries at all – tim_yates May 12 '22 at 20:04