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

1

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

Uranology answered 1/8, 2014 at 22:43 Comment(2)
Can't you implement hashCode and equals? Or annotate your class with @EqualsAndHashCodeExcommunication
(list2 - list1).foo will do as answered by @Excommunication but also note that in your original solution collect is redundant. you could simply say list1*.foo instead. It will perform better.Queen
E
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
Excommunication answered 2/8, 2014 at 0:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.