Suhas Kurade
Suhas Kurade

Reputation: 55

how to get common objects from array in groovy

def array1=[{id:1,name:"abc"},{id:2,name:"pqr"},{id:3,name:"xyz"}]

def array2=[{id:1,name:"abc"},{id:4,name:"efg"}]

The result Should be

[{id:1,name:"abc"}]

If id from array1 matches id of array2 then it gives that object

Upvotes: 2

Views: 930

Answers (1)

sann05
sann05

Reputation: 528

I guess arrays intersection will be helpful in your case:

array1.intersect(array2)

It returns common member from two arrays. But if you're looking for only id comparison:

 array1.findAll { elem ->
     array2.count { it.id == elem.id } > 0
 }

Upvotes: 2

Related Questions