Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to subtract one list of objects from another in Groovy?

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

like image 587
AndyJ Avatar asked Aug 01 '14 22:08

AndyJ


1 Answers

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
like image 181
tim_yates Avatar answered Nov 15 '22 10:11

tim_yates