Is there a groovier way to subtract one list from another when the elements are objects? I thought there might be a way to use minus but can't figure it out. This is what I have:
class item1 {
int foo
int getFoo(){return foo}
public item1(id_in){ foo = id_in }
}
def list1 = [new item1(10),new item1(11),new item1(13)]
def list2 = [new item1(11),new item1(12),new item1(14)]
// list3 = list2 - list1
def list3 = list2.findAll{ !(it.foo in list1.collect{it.foo}) }
// works
assert list3.collect{it.foo} == [12,14]
Which is pretty good really, but I was just curious if there was a better way. This question is pretty similar but seeks the intersection (coincidentally, just posted a few hours ago) but I think presupposes that the objects have an ID property. This is the reason I used my foo property - I don't want the solution to require some grails-like mojo related to "id" (if such a thing exists)).
You should be able to just do:
@groovy.transform.EqualsAndHashCode
class Item1 {
int foo
Item1(int too) {
this.foo = too
}
}
def list1 = [new Item1(10), new Item1(11), new Item1(13)]
def list2 = [new Item1(11), new Item1(12), new Item1(14)]
def foos = (list2 - list1).foo
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