5

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)).

Community
  • 1
  • 1
AndyJ
  • 1,204
  • 3
  • 14
  • 28
  • Can't you implement hashCode and equals? Or annotate your class with @EqualsAndHashCode – tim_yates Aug 01 '14 at 23:08
  • 2
    (list2 - list1).foo will do as answered by @tim_yates but also note that in your original solution collect is redundant. you could simply say list1*.foo instead. It will perform better. – Bilal Wahla Jun 07 '17 at 19:13

1 Answers1

11

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
tim_yates
  • 167,322
  • 27
  • 342
  • 338